-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFind Leaves of Binary Tree.kt
More file actions
40 lines (32 loc) · 975 Bytes
/
Find Leaves of Binary Tree.kt
File metadata and controls
40 lines (32 loc) · 975 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/**
* Example:
* var ti = TreeNode(5)
* var v = ti.`val`
* Definition for a binary tree node.
* class TreeNode(var `val`: Int) {
* var left: TreeNode? = null
* var right: TreeNode? = null
* }
*/
class Solution {
private val cachedNode: MutableMap<Int, MutableList<Int>> = mutableMapOf()
fun findLeaves(root: TreeNode?): List<List<Int>> {
groupByHeight(root)
var height = 1
var results: MutableList<List<Int>> = mutableListOf()
while (cachedNode[height] != null) {
results.add(cachedNode[height].orEmpty())
height++
}
return results
}
private fun groupByHeight(root: TreeNode?): Int {
if (root == null) {
return 0
}
val height = 1 + maxOf(groupByHeight(root?.left), groupByHeight(root?.right))
val nodes = cachedNode.getOrPut(height) { mutableListOf() }
nodes.add(root?.`val` ?: 0)
return height
}
}