A very simple C++ solution (0 ms runtime)


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

  • 0
    1

    elegant solution with destroying the tree structure!


  • 0

    Well, you made this problem the same as preorder traversal, except swap the order and the reverse call...


  • 0
    Q
    This post is deleted!

  • 0

    good! exactly, postorder = reverse(preorder + mirror reflection of lhs and rhs).
    But such an equivalence is not the key of this question.


Log in to reply
 

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