LeetCode-Binary Tree Level Order Traversal II

根据 104 题 Maximum Depth of Binary Tree 第二种使用队列层序遍历树的方法,直接层序遍历,然后逆序输出即可。

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
/**
* 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>> levelOrderBottom(TreeNode root) {
List<List<Integer>> lo=new ArrayList<List<Integer>>();
if(root==null) return lo;
Queue<TreeNode> q=new LinkedList<>();
q.offer(root);
while(!q.isEmpty()){
int size=q.size();
List<Integer> li=new ArrayList<>();
for(;size>0;size--){
TreeNode t=q.poll();
li.add(t.val);
if(t.left!=null) q.offer(t.left);
if(t.right!=null) q.offer(t.right);
}
lo.add(li);
}
Collections.reverse(lo);
return lo;
}
}