144. Binary Tree Preorder Traversal (Medium)
Given a binary tree, return thepreordertraversal of its nodes' values.
For example:
Given binary tree[1,null,2,3]
,
1
\
2
/
3
return[1,2,3]
.
Note:Recursive solution is trivial, could you do it iteratively?
Solution 1: Recursive, DFS O(n); O(h)
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
if (root == null) {
return res;
}
dfs(res, root);
return res;
}
private void dfs(List<Integer> res, TreeNode root) {
if (root == null) {
return;
}
res.add(root.val);
dfs(res, root.left);
dfs(res, root.right);
}
Solution 2: Iterative + Stack O(n); O(n)不太准确
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
if (root == null) {
return res;
}
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while (!stack.empty()) {
TreeNode cur = stack.pop();
res.add(cur.val);
if (cur.right != null) {
stack.push(cur.right); //FILO, first push right child into stack so that right child can last pop
}
if (cur.left != null) {
stack.push(cur.left);
}
}
return res;
}