diff --git a/solved/LeetCode/Challenges/2020/January/29.kt b/solved/LeetCode/Challenges/2020/January/29.kt new file mode 100644 index 00000000..3bb57707 --- /dev/null +++ b/solved/LeetCode/Challenges/2020/January/29.kt @@ -0,0 +1,22 @@ +class Solution { + data class Entry(val x: Int, val y: Int, val value: Int) + + val entries = mutableListOf() + + fun verticalTraversal(root: TreeNode?): List> { + dfs(root, 0, 0) + entries.sortBy { it.x } + return entries.groupBy { it.x }.values + .map{ it.sortedWith(compareBy({-it.y}, {it.value})) } + .map { l -> l.map {it.value} } + } + + fun dfs(root: TreeNode?, x: Int, y: Int) { + if (root == null) { + return + } + entries.add(Entry(x, y, root!!.`val`)) + dfs(root!!.left, x - 1, y - 1) + dfs(root!!.right, x + 1, y - 1) + } +}