kt: add «1123. Lowest Common Ancestor of Deepest Leaves»
URL: https://leetcode.com/problems/lowest-common-ancestor-of-deepest-leaves/ Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
b8bdec306c
commit
c6b7b034de
1 changed files with 18 additions and 0 deletions
18
kt/lowest-common-ancestor-of-deepest-leaves.kt
Normal file
18
kt/lowest-common-ancestor-of-deepest-leaves.kt
Normal file
|
@ -0,0 +1,18 @@
|
|||
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 }
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue