-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryTreeLevelOrderTraversal_II_hard.java
More file actions
executable file
·49 lines (44 loc) · 1.32 KB
/
BinaryTreeLevelOrderTraversal_II_hard.java
File metadata and controls
executable file
·49 lines (44 loc) · 1.32 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
package code.coder.lee.easy;
import code.coder.lee.common.TreeNode;
import java.util.*;
/**
* Created by bcc on 16/4/6.
*/
public class BinaryTreeLevelOrderTraversal_II_hard {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
if (root == null) {
return null;
}
Stack<List<Integer>> stack = new Stack<>();
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
levelOrder(stack, queue);
List<List<Integer>> lists = new ArrayList<>();
while (!stack.isEmpty()) {
lists.add(stack.pop());
}
return lists;
}
public void levelOrder(Stack<List<Integer>> stack, Queue<TreeNode> queue){
List<Integer> list = new ArrayList<>();
Queue<TreeNode> childQueue = new LinkedList<>();
/**
* 注意要先判断是否为空,否则会造成一直递归
*/
if(queue.isEmpty()){
return;
}
while (!queue.isEmpty()){
TreeNode node = queue.poll();
list.add(node.val);
if (node.left != null) {
childQueue.add(node.left);
}
if (node.right != null) {
childQueue.add(node.right);
}
}
stack.push(list);
levelOrder(stack, childQueue);
}
}