Skip to content

Commit a7d88ab

Browse files
committed
lowest common ancestor of a binary search tree
1 parent d61045d commit a7d88ab

File tree

1 file changed

+30
-0
lines changed
  • lowest-common-ancestor-of-a-binary-search-tree

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
class TreeNode(var `val`: Int = 0) {
2+
var left: TreeNode? = null
3+
var right: TreeNode? = null
4+
}
5+
6+
7+
class Solution {
8+
9+
// TC: O(H) - H: height of BST
10+
// SC: O(1) - while loop: X stack
11+
fun lowestCommonAncestor(root: TreeNode?, p: TreeNode?, q: TreeNode?): TreeNode? {
12+
13+
if (root == null || p == null || q == null) return null
14+
15+
// BST: left < parent < right
16+
var current = root
17+
while(current != null){
18+
if(current.`val` < p.`val` && current.`val` < q.`val`){
19+
current = current.right
20+
}
21+
else if(current.`val` > p.`val` && current.`val` > q.`val`){
22+
current = current.left
23+
}
24+
else return current
25+
}
26+
27+
return null
28+
}
29+
30+
}

0 commit comments

Comments
 (0)