[145] leetcode postorder traversal of a binary tree (binary)

Topic links: https://leetcode-cn.com/problems/binary-tree-postorder-traversal/

Title Description

Given a binary tree, it returns postorder traversal.

Example:

输入: [1,null,2,3]  
   1
    \
     2
    /
   3 

输出: [3,2,1]

Advanced : recursive algorithm is very simple, you can do it through an iterative algorithm?

Thinking

Non-recursive

1 by reversing nonrecursive preorder

The simple non-recursive preorder traversal modify 根->右->左the order of traversal, then the resulting inverted recursive sequence
obtained postorder traversal左->右->根

class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> ret;
        if(!root) return ret;
        stack<TreeNode *> s;
        s.push(root);
        while ( !s.empty()){
            root = s.top();
            s.pop();
            ret.push_back(root->val);
            if (root->left)
                s.push(root->left);
            if (root->right)
                s.push(root->right);
        }
        reverse(ret.begin(),ret.end());
        return ret;
    }
};

2 stack storage unvisited right child node

With the preorder and inorder traversal, as with a Stack memory has not traverse the right subtree node.
Remember the last node traversed by a last, last access point if the child is the right, indicating that the right subtree has traversed before.

class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> ret;
        if(!root) return ret;
        stack<TreeNode *> s;
        TreeNode *last = nullptr;
        while (root  || !s.empty()){
            while (root){
                s.push(root);
                root = root->left;
            }
            root = s.top();
            
            if(root->right == nullptr || root->right == last){
                ret.push_back(root->val);
                s.pop();
                last = root;
                root = nullptr;
            }
            else
                root = root->right;
        }
        return ret;
    }
};

Here Insert Picture Description

Guess you like

Origin blog.csdn.net/zjwreal/article/details/91795785