-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimple_107_BinaryTreeLevelOrderTraversalII.java
More file actions
60 lines (58 loc) · 1.36 KB
/
simple_107_BinaryTreeLevelOrderTraversalII.java
File metadata and controls
60 lines (58 loc) · 1.36 KB
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
52
53
54
55
56
57
58
59
60
import java.util.ArrayList;
import java.util.List;
/**
* created by zl on 2019/3/28 7:32
*
*给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
*
* 例如:
* 给定二叉树 [3,9,20,null,null,15,7],
*
* 3
* / \
* 9 20
* / \
* 15 7
* 返回其自底向上的层次遍历为:
*
* [
* [15,7],
* [9,20],
* [3]
* ]
*
*
*
*/
public class simple_107_BinaryTreeLevelOrderTraversalII
{
public List<List<Integer>> levelOrderBottom(TreeNode root)
{
List<List<Integer>> lists = new ArrayList<>();
func(lists, 0, root);
for (int i = 0, j = lists.size() - 1; i < j; i++, j--)
{
List<Integer> temp = lists.get(i);
lists.set(i, lists.get(j));
lists.set(j, temp);
}
return lists;
}
private void func(List<List<Integer>> lists, int level, TreeNode root)
{
if (root == null)
{
return;
}
if (lists.size() == level)
{
List<Integer> list = new ArrayList<>();
list.add(root.val);
lists.add(list);
} else {
lists.get(level).add(root.val);
}
func(lists, level + 1, root.left);
func(lists, level + 1, root.right);
}
}