树的bfs, 注意root可能是null

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
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
// @lc code=start
/**
* Definition for a binary tree node.
*/

class Solution {
/**
* 树的bfs, 注意root可能是null
*/
public List<List<Integer>> levelOrder(TreeNode root) {
Deque<TreeNode> que = new ArrayDeque<>();
if (root != null) que.addLast(root);
List<List<Integer>> ans = new ArrayList<>();
while (!que.isEmpty()) {
List<Integer> arr = new ArrayList<>();
int cnt = que.size();
for (int i = 0; i < cnt; i++) {
TreeNode tmp = que.removeFirst();
if (tmp.left != null) que.addLast(tmp.left);
if (tmp.right != null) que.addLast(tmp.right);
arr.add(tmp.val);
}
ans.add(arr);
}

return ans;
}
}

Comments
Recent Posts
Untitled
Categories
Tags
Website Info
Article Count :
2
Total Word Count :
1.6k
Unique Visitors :
Page Views :
Last Update :