-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBinaryTreeLevelOrderTraversalII.java
95 lines (68 loc) · 1.86 KB
/
BinaryTreeLevelOrderTraversalII.java
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
61
62
63
64
65
66
67
68
69
70
71
72
73
package binary_tree;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
/**
* @Author: Wenhang Chen
* @Description:给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
* <p>
* 例如:
* 给定二叉树 [3,9,20,null,null,15,7],
* <p>
* 3
* / \
* 9 20
* / \
* 15 7
* 返回其自底向上的层次遍历为:
* <p>
* [
* [15,7],
* [9,20],
* [3]
* ]
* @Date: Created in 14:21 3/5/2020
* @Modified by:
*/
public class BinaryTreeLevelOrderTraversalII {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
public List<List<Integer>> levelOrderBottom(TreeNode root) {
if(root == null)
return new ArrayList<>();
LinkedList<List<Integer>> result = new LinkedList<>();
LinkedList<TreeNode> queue = new LinkedList<>();
queue.add(root);
queue.addLast(null);
LinkedList<Integer> tempList = null;
while(!queue.isEmpty()){
TreeNode node = queue.removeFirst();
if(node == null){
if(tempList != null){
result.addFirst(tempList);
tempList = null;
queue.addLast(null);
continue;
}
} else {
if(tempList == null){
tempList = new LinkedList<>();
}
tempList.addLast(node.val);
if(node.left != null){
queue.addLast(node.left);
}
if(node.right != null){
queue.addLast(node.right);
}
}
}
return result;
}
}