forked from ByteByteGoHq/coding-interview-patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryTreeColumns.java
More file actions
68 lines (64 loc) · 2.21 KB
/
BinaryTreeColumns.java
File metadata and controls
68 lines (64 loc) · 2.21 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
61
62
63
64
65
66
67
68
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import DS.TreeNode;
/*
// Definition of TreeNode:
class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class BinaryTreeColumns {
public class Pair {
TreeNode node;
int column;
public Pair(TreeNode node, int column) {
this.node = node;
this.column = column;
}
}
public List<List<Integer>> binaryTreeColumns(TreeNode root) {
if (root == null) {
return new ArrayList<>();
}
Map<Integer, List<Integer>> columnMap = new HashMap<>();
int leftmostColumn, rightmostColumn;
leftmostColumn = rightmostColumn = 0;
Queue<Pair> queue = new ArrayDeque<>();
queue.offer(new Pair(root, 0));
while (!queue.isEmpty()) {
Pair pair = queue.poll();
TreeNode node = pair.node;
int column = pair.column;
if (node != null) {
// Add the current node's value to its corresponding list in the hash
// map.
List<Integer> columnList = columnMap.getOrDefault(column, new ArrayList<>());
columnList.add(node.val);
columnMap.put(column, columnList);
leftmostColumn = Math.min(leftmostColumn, column);
rightmostColumn = Math.max(rightmostColumn, column);
// Add the current node's children to the queue with their respective
// column ids.
queue.offer(new Pair(node.left, column - 1));
queue.offer(new Pair(node.right, column + 1));
}
}
// Construct the output list by collecting values from each column in the hash
// map in the correct order.
List<List<Integer>> res = new ArrayList<>();
for (int i = leftmostColumn; i <= rightmostColumn; i++) {
List<Integer> column = columnMap.get(i);
res.add(column);
}
return res;
}
}