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:
Matej Focko 2025-04-04 12:35:18 +02:00
parent b8bdec306c
commit c6b7b034de
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View 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 }
}