Skip to content

Commit 548c334

Browse files
committed
solve : lowest common ancestor of a binary search tree
1 parent 16f7887 commit 548c334

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
# TC : O(log n) because its a balanced tree
2+
# SC : O(1)
3+
class Solution:
4+
def lowestCommonAncestor(
5+
self, root: "TreeNode", p: "TreeNode", q: "TreeNode"
6+
) -> "TreeNode":
7+
current = root
8+
9+
# Return when they split to left and right
10+
while current:
11+
if p.val > current.val and q.val > current.val:
12+
current = current.right
13+
elif p.val < current.val and q.val < current.val:
14+
current = current.left
15+
else:
16+
return current

0 commit comments

Comments
 (0)