0ms c++ iterative solution


  • 0
    A
    /**
     * 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> a;
        stack<TreeNode*> s;
        vector<int> postorderTraversal(TreeNode* root) {
            if (root == NULL) return a;
            go (root);
            return a;
        }
        
        // iterative
        void go(TreeNode* t) {
            s.push(t);
            while(1) {
                // find most left node
                while (1) {
                    if (!s.empty() && s.top()->left && 
                    (a.empty() || !a.empty()  && a[a.size()-1]!=s.top()->left->val && (s.top()->right && a[a.size()-1]!=s.top()->right->val || !s.top()->right)) ) 
                        s.push(s.top()->left);
                    else break;
                }
                
                if (s.empty()) return;
                
                TreeNode* mostLeft = s.top();
                if (mostLeft->right && (a.empty() || !a.empty() && mostLeft->right->val != a[a.size()-1])) s.push(mostLeft->right);
                else {
                    s.pop();
                    a.push_back(mostLeft->val);
                }
            }
        }
        
        // void go(TreeNode* t){
        //     if (t == NULL) return;
        //     go(t->left);
        //     go(t->right);
        //     a.push_back(t->val);
        // }
    };
    

Log in to reply
 

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