mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-09 15:59:06 +01:00
problems: add „235. Lowest Common Ancestor of a Binary Search Tree“
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
15e6d58b12
commit
9fa6578ce7
1 changed files with 37 additions and 0 deletions
37
problems/lowest-common-ancestor-of-a-binary-search-tree.kt
Normal file
37
problems/lowest-common-ancestor-of-a-binary-search-tree.kt
Normal file
|
@ -0,0 +1,37 @@
|
|||
/**
|
||||
* 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
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue