Share my 3ms solution with c++


  • 0
    C
    class Solution {
    public:
    	vector<int> postorderTraversal(TreeNode* root) {
    		vector<int> rslt;
    		stack<TreeNode*> mystack;
    		TreeNode newroot(0);
    		TreeNode* p = NULL, *last;
    		newroot.right = root;
    		mystack.push(&newroot);
    		while (!mystack.empty()) {
    			last = p;
    			p = mystack.top();
    			
    			if (last != p->right) {
    				p = p->right;
    				while (p) {
    					mystack.push(p);
    					p = p->left;
    				}
    			} else {
    				if (p != &newroot) {
    					rslt.push_back(p->val);
    				}
    				mystack.pop();
    			}
    		}
    		return rslt;
    	}
    };

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

    I think my solution is similar to yours,and run well on computer,but cant accept no OJ.


Log in to reply
 

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