c++ 0ms iterative (predicated pop / replace)


  • 0
    G
    class Solution {
    public:
        vector<int> postorderTraversal(TreeNode* root) 
        {
            vector<int> result;
    
            deque<TreeNode*> queue;
            if(root != nullptr)
            {
                queue.push_back(root);
            }
            while(!queue.empty())
            {
                TreeNode* pNode = queue.front();
                result.push_back(pNode->val);
                TreeNode* pRight = pNode->right;
                TreeNode* pLeft = pNode->left;
                if(pLeft != nullptr)
                {
                    pNode->left = pLeft->left;
                    pNode->right = pLeft->right;
                    pNode->val = pLeft->val;
                }
                else
                {
                    queue.pop_front();
                }
                
                if(pRight != nullptr)
                {
                    queue.push_front(pRight);
                }
            }
            reverse(result.begin(), result.end());
            return result;
        }
    };
    

  • 0
    A

    @g3n1us Honestly, this is just preorder. The reverse is simply a cheap cheat. If an interviewer sees this, they would ask you to implement it again without using "reverse". You should be prepared.


Log in to reply
 

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