C++ solution with a stack


  • 0
    K
    /**
     * 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) {
        stack<TreeNode*> stk;
        TreeNode *p = root;
        vector<int> ans;
        while(!stk.empty() || p){
            if(p == NULL){
                if(stk.top()->right == NULL){
                    p = stk.top();stk.pop();ans.push_back(p->val);
                    while(!stk.empty() && p == stk.top()->right){
                        p = stk.top();stk.pop();ans.push_back(p->val);
                    }
                    p = NULL;//important!!
                 }else{
                    p = stk.top()->right;
                }
            } else{
                stk.push(p);
                p=p->left;
            }
            
        }
        return ans;
    }
    
    };

  • 0
    S

    It's not a proper way. You shouldn't change the structure of tree when traversing. Actually, you destroy the tree.


Log in to reply
 

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