forked from anishLearnsToCode/leetcode-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BinaryTreeLevelOrderTraversalII.java
53 lines (46 loc) · 1.45 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
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class BinaryTreeLevelOrderTraversalII {
private static class Pair {
TreeNode tree;
int level;
Pair(TreeNode tree, int level) {
this.tree = tree;
this.level = level;
}
}
public List<List<Integer>> levelOrderBottom(TreeNode root) {
List<List<Integer>> levels = new ArrayList<>();
if (root == null) {
return levels;
}
LinkedList<Pair> queue = new LinkedList<>();
queue.add(new Pair(root, 0));
List<Integer> level = new ArrayList<>();
int currentLevel = 0;
while (!queue.isEmpty()) {
Pair pair = queue.pop();
if (pair.level > currentLevel) {
levels.add(level);
level = new ArrayList<>();
currentLevel = pair.level;
}
level.add(pair.tree.val);
addChildrenToQueue(pair, queue);
}
levels.add(level);
Collections.reverse(levels);
return levels;
}
private static void addChildrenToQueue(Pair pair, Queue<Pair> queue) {
if (pair.tree.left != null) {
queue.add(new Pair(pair.tree.left, pair.level + 1));
}
if (pair.tree.right != null) {
queue.add(new Pair(pair.tree.right, pair.level + 1));
}
}
}