My simple c++ solution


  • 3
    K
    class Solution {
    public:
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int>res;
        stack<TreeNode *>stack;
        TreeNode * temp;
        if(!root)return res;
        stack.push(root);
        while(!stack.empty())
        {
            temp=stack.top();
            stack.pop();
            res.insert(res.begin(), temp->val);
            if(temp->left)stack.push(temp->left);
            if(temp->right)stack.push(temp->right);
        }
        return res;
    }
    

    };


  • 0
    W

    Thanks for sharing!. Very clever method to insert the output to the front instead of the end.
    But it seems inefficient to insert at the front of a vector, it needs to move all existing elements backwards for every insert. Maybe we can push_back as normal, but reverse the vector at the end.


Log in to reply
 

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