My 0ms iterative solution. Using 1 stack.


  • 0
    A
      vector<int> preorderTraversal(TreeNode* root) {
                stack<TreeNode*> nodes;
                vector<int> ans;
                TreeNode* curr = root;
                while(curr || !nodes.empty()){
                    if(curr){
                        nodes.push(curr);
                        ans.push_back(curr->val);
                        curr = curr->left;
                    }
                    else{
                        curr = nodes.top();
                        nodes.pop();
                        curr = curr->right;
                    }
                }
                return ans;
                
           }

Log in to reply
 

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