One stack Accepted


  • 1
    A
    class Solution {
    public:
        vector<int> postorderTraversal(TreeNode *root) {
            stack<TreeNode *> st;
            vector<int> vRet;
            TreeNode *p, *pre = root;
            
            if (!root) return vRet;
            p = root->left;
            st.push(root);
            while (!st.empty() )
            {
                while (p) { st.push(p); p = p->left; }
    			p = st.top();
    			while (!p->right || pre==p->right)
    			{
    				vRet.push_back(p->val);
    				pre = p;
    				st.pop();
    				if (st.empty() ) break;
    				p = st.top();
    			}
    			p = p->right;
            }
            return vRet;
        }
    };

Log in to reply
 

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