URL: https://leetcode.com/problems/lowest-common-ancestor-of-deepest-leaves/ Signed-off-by: Matej Focko <me@mfocko.xyz>
18 lines
614 B
Kotlin
18 lines
614 B
Kotlin
class Solution {
|
|
private fun dfs(node: TreeNode?): Pair<TreeNode?, Int> =
|
|
when {
|
|
node == null -> null to 0
|
|
else -> {
|
|
val (left, leftDepth) = dfs(node.left)
|
|
val (right, rightDepth) = dfs(node.right)
|
|
|
|
when {
|
|
leftDepth < rightDepth -> right to rightDepth + 1
|
|
leftDepth > rightDepth -> left to leftDepth + 1
|
|
else -> node to leftDepth + 1
|
|
}
|
|
}
|
|
}
|
|
|
|
fun lcaDeepestLeaves(root: TreeNode?): TreeNode? = dfs(root).let { (node, _) -> node }
|
|
}
|