leetcode 107. Binary Tree Level Order Traversal II


  1. Binary Tree Level Order Traversal II:题目链接

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
38
39
40
41
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
// 层序遍历这棵树 将第i层的结点全部加入到一个list中 最后再将该list压入栈中 最后将栈中结果集出栈就是answer
// 其实也可以不用栈 用java里面的一个方法 res.add(0, 该层的结点集合) 就可以起到压栈再出栈的效果
public List<List<Integer>> levelOrderBottom(TreeNode root) {
List<List<Integer>> res= new ArrayList<>();
if (root == null) {
return res;
}
Queue<TreeNode> queue = new LinkedList<>();
Stack<List<Integer>> stack = new Stack<>();
queue.offer(root);
while (!queue.isEmpty()) {
List<Integer> list = new ArrayList<>();
for (int size = queue.size(); size > 0; --size) {
TreeNode front = queue.poll();
list.add(front.val);
if (front.left != null) {
queue.offer(front.left);
}
if (front.right != null) {
queue.offer(front.right);
}
}
stack.push(list);
}

while (!stack.isEmpty()) {
res.add(stack.pop());
}
return res;
}
}
文章目录
  1. 1. BFS
|