Skip to content

Commit 89fdd8e

Browse files
committed
Add solution for 235. Lowest Common Ancestor of a Binary Search Tree
1 parent 012d3f3 commit 89fdd8e

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
"""
2+
235. Lowest Common Ancestor of a Binary Search Tree
3+
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/
4+
"""
5+
6+
# Definition for a binary tree node.
7+
class TreeNode:
8+
def __init__(self, x):
9+
self.val = x
10+
self.left = None
11+
self.right = None
12+
13+
"""
14+
Solution:
15+
- If both p and q are greater than the root, the lowest common ancestor is in the right subtree.
16+
- If both p and q are less than the root, the lowest common ancestor is in the left subtree.
17+
- Otherwise, the root is the lowest common ancestor.
18+
19+
Time complexity: O(N)
20+
- The function is called recursively for each node
21+
Space complexity: O(N)
22+
- Maximum depth of the recursion is the height of the tree
23+
"""
24+
25+
class Solution:
26+
def lowestCommonAncestor(
27+
self, root: "TreeNode", p: "TreeNode", q: "TreeNode"
28+
) -> "TreeNode":
29+
30+
if p.val > root.val and q.val > root.val:
31+
return self.lowestCommonAncestor(root.right, p, q)
32+
33+
elif p.val < root.val and q.val < root.val:
34+
return self.lowestCommonAncestor(root.left, p, q)
35+
else:
36+
return root

0 commit comments

Comments
 (0)