Skip to content

Commit 1bbdd53

Browse files
committed
solve: lowestCommonAncestorOfABinarySearchTree
1 parent 19ff763 commit 1bbdd53

File tree

1 file changed

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

1 file changed

+21
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# Time Complexity: O(log N) on average (for balanced BST), worst case O(N) (skewed tree).
2+
# Space Complexity: O(1) - don't use extra space, just a few variables.
3+
4+
class Solution:
5+
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
6+
# start from the root
7+
node = root
8+
9+
while node:
10+
if p.val > node.val and q.val > node.val:
11+
# both p and q are in the right subtree, so move right
12+
node = node.right
13+
elif p.val < node.val and q.val < node.val:
14+
# both p and q are in the left subtree, so move left
15+
node = node.left
16+
else:
17+
# found the split point where one is on the left and the other is on the right
18+
# or when we reach p or q directly (since a node can be its own ancestor)
19+
return node
20+
21+
return None

0 commit comments

Comments
 (0)