Please help with the solution (C++)


  • 0
    J

    The following solution cannot pass with input {1}, I cannot find where the problem is. Please help.

      class Solution {
        public:
            vector<int> postorderTraversal(TreeNode *root) {
                vector<int> v;
                if (!root)
                    return v;
                    
                stack<TreeNode*> q;
                unordered_set<long> s;
                TreeNode* l;
                l = root;
                q.push(l);
                while (!q.empty()) {
                    if (!l->left && !s.count((long) l)) {
                        l = l->left;
                        q.push(l);
                    }
                    else if (!l->right && !s.count((long) l)) {
                        l = l->right;
                        q.push(l);
                    }
                    else { //leaf or a non-leaf node whose children are all visited
                        s.insert((long) l);
                        v.push_back(l->val);
                        l = q.top();
                        q.pop();
                    }
                }
                return v;
            }
        };

Log in to reply
 

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