0ms C++ single stack solution (easy to understand)


  • 0
    N
    #include <stack>
    class Solution {
    public:
        vector<int> postorderTraversal(TreeNode* root) {
            vector<int> result;
            TreeNode *curr = root;
            stack<TreeNode*> container;
            while(curr || container.size() ){
                if(curr){
                       container.push(curr);
                       curr = curr->left ? curr->left : curr->right;
                } else {
                    curr = container.top();
                    result.push_back(curr->val);
                    container.pop();
                    if( container.size() && container.top()->left == curr){
                        curr = container.top()->right;
                    } else {
                        curr = NULL;
                    }
                }
            }
            return result;
        }
    };
    

Log in to reply
 

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