C++ iterative solution(0ms) with a stack


  • 5
    G
    class Solution {
    public:
        vector<int> postorderTraversal(TreeNode* root) {
            vector<int> ret;
            if(root==NULL)return ret;
            stack<TreeNode*> st;
            st.push(root);
            while(!st.empty())
            {
                TreeNode *curr=st.top();
                st.pop();
                if(curr->left)st.push(curr->left);
                if(curr->right)st.push(curr->right);
                ret.push_back(curr->val);
            }
            reverse(ret.begin(),ret.end());
            return ret;
        }
    };

Log in to reply
 

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