-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path235.py
20 lines (18 loc) · 809 Bytes
/
235.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# https://neetcode.io/problems/lowest-common-ancestor-in-binary-search-tree
# https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/description/
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def lowestCommonAncestor(self, root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode:
if not root:
return None
if min(p.val, q.val) <= root.val and root.val <= max(p.val, q.val):
return root
if root.val > max(p.val, q.val):
return self.lowestCommonAncestor(root.left, p, q)
if root.val < min(p.val, q.val):
return self.lowestCommonAncestor(root.right, p, q)