Concise 0ms c++ solution,no reverse or insert operation.


  • 0
    K
        vector<int> postorderTraversal(TreeNode* root) {
            vector<int> res;
            if(!root) return res;
            stack<TreeNode*> s;
            s.push(root);
            TreeNode* node = root;
            while(!s.empty()){
                TreeNode* cur = s.top();
                if((!cur->left && !cur->right) || node == cur->right){ //this node is leaf or its right child has met,output this node.
                    res.push_back(cur->val);
                    node = cur;
                    s.pop();
                }else if(node == cur){ //first met this node,go left.
                    node = cur->left;
                    if(cur->left){
                        s.push(cur->left);
                    }
                }else{ //left child has met,go right.
                    node = cur->right;
                    if(cur->right){
                        s.push(cur->right);
                    }
                }
            }
            return res;
        }
    

Log in to reply
 

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