-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy path102. Binary Tree Level Order Traversal.java
executable file
·106 lines (85 loc) · 2.66 KB
/
102. Binary Tree Level Order Traversal.java
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
M
tags: Tree, BFS, DFS
time: O(n)
space: O(n)
如题.
#### Method1: BFS
- 最普通,Non-recursive: BFS, queue, 用个queue.size()来end for loop:换行。
- 或者用两个queue. 当常规queue empty,把backup queue贴上去
#### Method2: DFS
- 每个level都应该有个ArrayList. 那么用一个int level来查看:是否每一层都有了相应的ArrayList。
- 如果没有,就加上一层。
- 之后每次都通过DFS在相应的level上面加数字。
```
/*
Given a binary tree, return the level order traversal of its nodes' values.
(ie, from left to right, level by level).
Example
Given binary tree {3,9,20,#,#,15,7},
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]
Challenge
Challenge 1: Using only 1 queue to implement it.
Challenge 2: Use DFS algorithm to do it.
Tags Expand
Queue Binary Tree Breadth First Search Binary Tree Traversal Uber LinkedIn Facebook
*/
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> rst = new ArrayList<>();
if (root == null) return rst;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int size = queue.size();
List<Integer> list = new ArrayList<>();
while (size-- > 0) {
TreeNode node = queue.poll();
list.add(node.val);
if(node.left != null) queue.offer(node.left);
if(node.right != null) queue.offer(node.right);
}
rst.add(list);
}
return rst;
}
}
//Method2: DFS
//Recursive with dfs: use a level to track. Add curr into corresponding level; each level > rst.size(), add a new [].
//Note: rst is a ArrayList<ArrayList<Integer>>, where each level is a arraylist; that is why we can add [] into rst to represent a level.
public class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<>();
if (root == null) return result;
dfs(root, 0, result);
return result;
}
public void dfs(TreeNode root, int level, List<List<Integer>> rst) {
if (root == null) return;
if (level >= rst.size()) rst.add(new ArrayList<>());
rst.get(level).add(root.val);
dfs(root.left, level + 1, rst);
dfs(root.right, level + 1, rst);
}
}
```