My solution with stack


  • 0
    W

    class Solution {
    public:
    vector<int> postorderTraversal(TreeNode root) {
    vector<int> ret;
    map<TreeNode
    , int> visited;
    if (root == NULL)
    {
    return ret;
    }

        TreeNode *cur = root;
        stack<TreeNode *> st;
        st.push(cur);
        while (st.size() > 0)
        {
            cur = st.top();
            if ((cur->left == NULL || visited.count(cur->left) > 0)
                && (cur->right == NULL || visited.count(cur->right) >0))
                {
                    ret.push_back(cur->val);
                    st.pop();
                    visited[cur] = 1;
                    continue;
                }
            if (cur->right != NULL)
            {
                st.push(cur->right);
            }
            
            if (cur->left != NULL)
            {
                st.push(cur->left);
            }
        }
    }

Log in to reply
 

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