C++ iterative solution


  • 0
    H
    class Solution {
    public:
        vector<int> preorderTraversal(TreeNode* root) {
            vector<int> ans;
            stack<TreeNode *> stk;
            TreeNode *last = nullptr; 
            while(root || !stk.empty()) {
                if(root) {
                    ans.push_back(root->val);
                    stk.push(root);
                    root = root->left;
                }
                else {
                    root = stk.top();
                    if(root->right && root->right != last) root = root->right;
                    else {
                        stk.pop();
                        last = root;
                        root = nullptr;
                    }
                }
            }
            return ans;
        }
    };
    

Log in to reply
 

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