标签:
题目原型:
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).
For example:
Given binary tree {3,9,20,#,#,15,7}
,
1
2
3
4
5
|
3 / \ 9 20 / \ 15 7 |
return its bottom-up level order traversal as:
1
2
3
4
5
|
[ [ 15 , 7 ] [ 9 , 20 ], [ 3 ], ] |
基本思路:
由于是从底向上,所以用到了栈。
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
|
public ArrayList> levelOrderBottom(TreeNode root) { Stack> stack = new Stack>(); ArrayList> list = new ArrayList>(); ArrayList<TREENODE> nodeSet = new ArrayList<TREENODE>(); ArrayList<TREENODE> tmp ; ArrayList<INTEGER> numSet ; if (root!= null ) { nodeSet.add(root); while (nodeSet.size()> 0 ) { tmp = new ArrayList<TREENODE>(); numSet = new ArrayList<INTEGER>(); //添加到stack中 for (TreeNode tn : nodeSet) numSet.add(tn.val); //添加到stack中 stack.push(numSet); //求下一层的节点 for (TreeNode it : nodeSet) { if (it.left!= null ) tmp.add(it.left); if (it.right!= null ) tmp.add(it.right); } nodeSet = tmp; } //添加到list中 while (stack.size()> 0 ) { ArrayList<INTEGER> rs = stack.pop(); list.add(rs); } } return list; } |
标签:
原文地址:http://www.cnblogs.com/firstdream/p/5315018.html