8/17/2021
The algorithms are similar as 94. Inorder Traversal.
C++
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> ans;
helper(root, ans);
return ans;
}
void helper(TreeNode* root, vector<int>& ans){
if(!root){
return;
}
ans.push_back(root->val);
helper(root->left, ans);
helper(root->right, ans);
}
};
Python
class Solution:
def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
ans = []
self.helper(root, ans)
return ans
def helper(self, root, ans):
if not root:
return
ans.append(root.val)
self.helper(root.left, ans)
self.helper(root.right, ans)
- Go all the way to the left and push every element.
C++
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> ans;
TreeNode* cur = root;
stack<TreeNode*> treeStack;
while(cur || !treeStack.empty()){
while(cur){
treeStack.push(cur);
ans.push_back(cur->val);
cur = cur->left;
}
cur = treeStack.top();
treeStack.pop();
cur = cur->right;
}
return ans;
}
};
Python
class Solution:
def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
ans = []
treeStack = []
cur = root
while cur or treeStack:
# add cur to stack and go all the way to the left
while cur:
ans.append(cur.val)
treeStack.append(cur)
cur = cur.left
cur = treeStack.pop()
cur = cur.right
return ans
- pop first and add it to ans
- push right and push left
class Solution:
def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
if not root:
return []
stack1 = []
ans = []
stack1.append(root)
while stack1:
cur = stack1.pop()
ans.append(cur.val)
# or using if not top, continue
if cur.right:
stack1.append(cur.right)
if cur.left:
stack1.append(cur.left)
return ans