preorder + reverse: using stack


  • 0
    P
    /**
     * 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> ans;
            stack<TreeNode *> stk;
            while(root || !stk.empty()){
                while(root){
                    ans.push_back(root->val);
                    if(root->left) stk.push(root->left);
                    root = root->right;
                }
                if(!stk.empty()){
                    root = stk.top();
                    stk.pop();
                }
            }
            reverse(ans.begin(),ans.end());
            return ans;
        }
    };
    

Log in to reply
 

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