9-liner using stack in reversed pre-order traversal


  • 0
        vector<int> postorderTraversal(TreeNode* r) {
            if (!r) return {};
            vector<int> rev;
            stack<TreeNode*> s; s.push(r);
            
            while (!s.empty()) {
                auto cur = s.top(); s.pop();
                rev.push_back(cur->val);
                if (cur->left) s.push(cur->left);
                if (cur->right) s.push(cur->right);
            }
            return vector<int>(rev.rbegin(), rev.rend());
        }
    

Log in to reply
 

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