05 August 2008
Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level).
For example:
Given binary tree ‘[3,9,20,null,null,15,7]’,
1
2
3
4
5
3
/ \
9 20
/ \
15 7
return its level order traversal as:
1
2
3
4
5
[
[3],
[9,20],
[15,7]
]
层序遍历,掌握BFS和递归的写法。
BFS
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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if (root == null) {
return result;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
int size = queue.size();// 每一层的元素个数
List<Integer> level = new ArrayList();
while (size > 0) {//BFS
TreeNode node = queue.poll();
level.add(node.val);
if (node.left != null) {
queue.add(node.left);
}
if (node.right != null) {
queue.add(node.right);
}
size--;
}
result.add(level);
}
return result;
}
}
递归(层序遍历各种题总结-DFS实现)
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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if (root == null) {
return result;
}
levelOrderHelper(result, root, 0);
return result;
}
private void levelOrderHelper(List<List<Integer>> result, TreeNode current,
int level) {
if (current == null) {
return;
}
//先DFS一条路走到底把每一层的arraylist创建好,然后回溯的时候在call stack中取到
// level的值,把对应的层的值传进去
if (result.size() == level) {
result.add(new ArrayList<Integer>());
}
result.get(level).add(current.val);
levelOrderHelper(result, current.left, level + 1);
levelOrderHelper(result, current.right, level + 1);
}
}