Skip to content

Commit 04b777d

Browse files
author
Thuy Trinh
committed
Solution for "Binary Tree Vertical Order Traversal"
1 parent a80bd84 commit 04b777d

File tree

2 files changed

+79
-0
lines changed

2 files changed

+79
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package leetcode.btverticalordertraversal
2+
3+
import leetcode.binarytreeboundary.TreeNode
4+
import java.util.*
5+
6+
/**
7+
* https://leetcode.com/problems/binary-tree-vertical-order-traversal/description/
8+
*/
9+
class Solution {
10+
fun verticalOrder(root: TreeNode?): List<List<Int>> = when {
11+
root != null -> {
12+
val m = root.travelVertically()
13+
m.keys.sorted()
14+
.map { m[it] ?: mutableListOf() }
15+
}
16+
else -> emptyList()
17+
}
18+
19+
private fun TreeNode.travelVertically(): MutableMap<Int, MutableList<Int>> {
20+
val map = mutableMapOf<Int, MutableList<Int>>()
21+
val xCache = mutableMapOf(this to 0)
22+
val nodes = LinkedList<TreeNode>()
23+
nodes.offer(this)
24+
while (nodes.isNotEmpty()) {
25+
val node = nodes.poll()
26+
val x = xCache[node] ?: 0
27+
map.getOrPut(x) { mutableListOf() }.add(node.`val`)
28+
node.left?.let {
29+
nodes.offer(it)
30+
xCache[it] = x - 1
31+
}
32+
node.right?.let {
33+
nodes.offer(it)
34+
xCache[it] = x + 1
35+
}
36+
}
37+
return map
38+
}
39+
}
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package leetcode.btverticalordertraversal
2+
3+
import leetcode.binarytreeboundary.node
4+
import org.amshove.kluent.shouldEqual
5+
import org.junit.Test
6+
7+
class SolutionTest {
8+
@Test
9+
fun test() {
10+
Solution().verticalOrder(node(3) {
11+
left = node(9)
12+
right = node(20) {
13+
left = node(15)
14+
right = node(7)
15+
}
16+
}).shouldEqual(listOf(
17+
listOf(9),
18+
listOf(3, 15),
19+
listOf(20),
20+
listOf(7)
21+
))
22+
23+
Solution().verticalOrder(node(3) {
24+
left = node(9) {
25+
left = node(4)
26+
right = node(0)
27+
}
28+
right = node(8) {
29+
left = node(1)
30+
right = node(7)
31+
}
32+
}).shouldEqual(listOf(
33+
listOf(4),
34+
listOf(9),
35+
listOf(3, 0, 1),
36+
listOf(8),
37+
listOf(7)
38+
))
39+
}
40+
}

0 commit comments

Comments
 (0)