2022-08-12 22:10:33 +02:00
|
|
|
/**
|
|
|
|
* Definition for a binary tree node.
|
|
|
|
* class TreeNode(var `val`: Int = 0) {
|
|
|
|
* var left: TreeNode? = null
|
|
|
|
* var right: TreeNode? = null
|
|
|
|
* }
|
|
|
|
*/
|
|
|
|
|
|
|
|
class Solution {
|
2024-05-17 18:23:38 +02:00
|
|
|
fun lowestCommonAncestor(
|
|
|
|
root: TreeNode?,
|
|
|
|
p: TreeNode?,
|
|
|
|
q: TreeNode?,
|
|
|
|
): TreeNode? {
|
2022-08-12 22:10:33 +02:00
|
|
|
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
|
|
|
|
}
|
|
|
|
}
|