My C++ iterative method


  • 1
    L
    class Solution {
    public:
        vector<int> postorderTraversal(TreeNode* root) {
            vector<int> res;
            
            if(!root)
                return res;
            
            stack<TreeNode* > s;
            TreeNode* temp = root;
            TreeNode* pre;
            
            while(temp || !s.empty())
            {
                while(temp)
                {
                    s.push(temp);
                    temp = temp->left;
                }
                
                if(s.top()->right && pre != s.top()->right)
                {
                    temp = s.top()->right;
                }
                else
                {
                    res.push_back(s.top()->val);
                    pre = s.top();
                    s.pop();
                }
                
            }
            
            return res;
        }
        
    };

Log in to reply
 

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