1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-14 09:59:41 +01:00
LeetCode/problems/kt/lowest-common-ancestor-of-a-binary-search-tree.kt
Matej Focko 333866d1bc
chore: split solutions by language
Signed-off-by: Matej Focko <mfocko@redhat.com>
2023-06-02 17:19:02 +02:00

37 lines
973 B
Kotlin

/**
* Definition for a binary tree node.
* class TreeNode(var `val`: Int = 0) {
* var left: TreeNode? = null
* var right: TreeNode? = null
* }
*/
class Solution {
fun lowestCommonAncestor(root: TreeNode?, p: TreeNode?, q: TreeNode?): TreeNode? {
var ancestor: TreeNode? = null
var pTrack = root
var qTrack = root
while (pTrack == qTrack && pTrack != null && qTrack != null) {
ancestor = pTrack
if (pTrack!!.`val` == p!!.`val`) {
return p
} else if (p!!.`val` < pTrack!!.`val`) {
pTrack = pTrack.left
} else {
pTrack = pTrack.right
}
if (qTrack!!.`val` == q!!.`val`) {
return q
} else if (q!!.`val` < qTrack!!.`val`) {
qTrack = qTrack.left
} else {
qTrack = qTrack.right
}
}
return ancestor
}
}