Skip to content

Commit c02611c

Browse files
committed
Add Binary Tree Columns
1 parent b0a0ff0 commit c02611c

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

kotlin/Trees/BinaryTreeColumns.kt

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import java.util.LinkedList
2+
import ds.TreeNode
3+
4+
/*
5+
Definition of TreeNode:
6+
7+
data class TreeNode(
8+
var value: Int,
9+
var left: TreeNode? = null,
10+
var right: TreeNode? = null
11+
)
12+
*/
13+
14+
fun binaryTreeColumns(root: TreeNode?): List<List<Int>> {
15+
if (root == null) {
16+
return emptyList()
17+
}
18+
val columnMap = hashMapOf<Int, MutableList<Int>>()
19+
var leftmostColumn = 0
20+
var rightmostColumn = 0
21+
val queue = LinkedList<Pair<TreeNode?, Int>>()
22+
queue.add(root to 0)
23+
24+
while (queue.isNotEmpty()) {
25+
val (node, column) = queue.removeFirst()
26+
if (node != null) {
27+
// Add the current node's value to its corresponding list in the hash
28+
// map.
29+
columnMap.computeIfAbsent(column) { mutableListOf() }.add(node.value)
30+
leftmostColumn = minOf(leftmostColumn, column)
31+
rightmostColumn = maxOf(rightmostColumn, column)
32+
// Add the current node's children to the queue with their respective
33+
// column ids.
34+
queue.add(node.left to column - 1)
35+
queue.add(node.right to column + 1)
36+
}
37+
}
38+
39+
// Construct the output list by collecting values from each column in the hash
40+
// map in the correct order.
41+
return (leftmostColumn..rightmostColumn).map { columnMap[it] ?: emptyList() }
42+
}

0 commit comments

Comments
 (0)