Binary Tree Level Order Traversal II

Given a binary tree, return the bottom-up level order traversal of its nodes’ values. (ie, from left to right, level by level from leaf to root).

描述

层序遍历,自底向上

分析

自顶向下遍历,将新的一层插入到最前面,lists.add(0, arrayList)

代码

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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/

public class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {

List<List<Integer>> lists = new ArrayList<List<Integer>>();

if (root == null) {
return lists;
}

Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(root);

int count = 0, n = 1;

while (!queue.isEmpty()) {

ArrayList arrayList = new ArrayList<Integer>();

while ((--n) >= 0) {

TreeNode treeNode = queue.poll();
arrayList.add(treeNode.val);

if (treeNode.left != null) {
queue.offer(treeNode.left);
count++;
}

if (treeNode.right != null) {
queue.offer(treeNode.right);
count++;
}
}

n = count;
count = 0;
lists.add(0, arrayList); //lists.add(arrayList);(自顶向下)
}

return lists;
}
}