Skip to content

Commit 95c1e76

Browse files
committed
add: BinaryTreeColumns
1 parent 3bcd176 commit 95c1e76

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

java/Trees/BinaryTreeColumns.java

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
import java.util.ArrayDeque;
2+
import java.util.ArrayList;
3+
import java.util.HashMap;
4+
import java.util.List;
5+
import java.util.Map;
6+
import java.util.Queue;
7+
8+
import DS.TreeNode;
9+
10+
/*
11+
// Definition of TreeNode:
12+
class TreeNode {
13+
public int val;
14+
public TreeNode left;
15+
public TreeNode right;
16+
public TreeNode(int val) {
17+
this.val = val;
18+
}
19+
}
20+
*/
21+
22+
public class BinaryTreeColumns {
23+
public class Pair {
24+
TreeNode node;
25+
int column;
26+
public Pair(TreeNode node, int column) {
27+
this.node = node;
28+
this.column = column;
29+
}
30+
}
31+
32+
public List<List<Integer>> binaryTreeColumns(TreeNode root) {
33+
if (root == null) {
34+
return new ArrayList<>();
35+
}
36+
Map<Integer, List<Integer>> columnMap = new HashMap<>();
37+
int leftmostColumn, rightmostColumn;
38+
leftmostColumn = rightmostColumn = 0;
39+
Queue<Pair> queue = new ArrayDeque<>();
40+
queue.offer(new Pair(root, 0));
41+
while (!queue.isEmpty()) {
42+
Pair pair = queue.poll();
43+
TreeNode node = pair.node;
44+
int column = pair.column;
45+
if (node != null) {
46+
// Add the current node's value to its corresponding list in the hash
47+
// map.
48+
List<Integer> columnList = columnMap.getOrDefault(column, new ArrayList<>());
49+
columnList.add(node.val);
50+
columnMap.put(column, columnList);
51+
leftmostColumn = Math.min(leftmostColumn, column);
52+
rightmostColumn = Math.max(rightmostColumn, column);
53+
// Add the current node's children to the queue with their respective
54+
// column ids.
55+
queue.offer(new Pair(node.left, column - 1));
56+
queue.offer(new Pair(node.right, column + 1));
57+
}
58+
}
59+
// Construct the output list by collecting values from each column in the hash
60+
// map in the correct order.
61+
List<List<Integer>> res = new ArrayList<>();
62+
for (int i = leftmostColumn; i <= rightmostColumn; i++) {
63+
List<Integer> column = columnMap.get(i);
64+
res.add(column);
65+
}
66+
return res;
67+
}
68+
}

0 commit comments

Comments
 (0)