MCPcopy Create free account
hub / github.com/ByteByteGoHq/coding-interview-patterns / BinaryTreeColumns

Class BinaryTreeColumns

java/Trees/BinaryTreeColumns.java:22–68  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

20 */
21
22public 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}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected