A very easy and understandable solution, without complicated tricks


  • 0
    W

    The intuition is very straightforward, postorder traversal is the reverse of the "root->right->left" preorder traversal.

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        vector<int> postorderTraversal(TreeNode* root) {
            vector<int> ret;
            stack<TreeNode*> s;
            if(root == nullptr)
                return ret;
            s.push(root);
            TreeNode* temp;
            while(!s.empty()){
                temp = s.top();
                s.pop();
                ret.push_back(temp->val);
                if(temp->left)
                    s.push(temp->left);
                if(temp->right)
                    s.push(temp->right);
                
            }
            reverse(ret.begin(),ret.end());
            return ret;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.