144. Binary Tree Preorder Traversal

DFS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
// root -> left -> right

List<Integer> list = new LinkedList<>();

recur(list, root);

return list;
}

private void recur(List<Integer> list, TreeNode node) {
if (node == null) {
return;
}

list.add(node.val);
recur(list, node.left);
recur(list, node.right);
}
}

Iterate

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
// root -> left -> right

List<Integer> resultList = new ArrayList<>();

Stack<TreeNode> stack = new Stack<>();
if (root != null) {
stack.push(root);
}

while (!stack.isEmpty()) {
TreeNode node = stack.pop();
resultList.add(node.val);

if (node.right != null) {
// 右节点先入栈,后出栈,保证在左节点之后遍历
stack.push(node.right);
}
if (node.left != null) {
// 左节点后入栈,先出栈,保证在右节点之前遍历
stack.push(node.left);
}
}

return resultList;
}
}

Iterate

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
// root -> left -> right

List<Integer> resultList = new ArrayList<>();

Stack<TreeNode> stack = new Stack<>();
while (root != null || !stack.isEmpty()) {
while (root != null) {
stack.push(root);
resultList.add(root.val);
root = root.left;
}

// now: root is null
TreeNode node = stack.pop(); // 回溯
if (node.right != null) {
root = node.right;
}
}

return resultList;
}
}

References

144. Binary Tree Preorder Traversal