-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path231. Lowest-Common-Ancestor-of-a-Binary-Search-Tree
49 lines (38 loc) · 1.31 KB
/
231. Lowest-Common-Ancestor-of-a-Binary-Search-Tree
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if not root:
return None
if root == p or root == q:
return root
leftAncestor = self.lowestCommonAncestor(root.left,p,q)
rightAncestor = self.lowestCommonAncestor(root.right,p,q)
if leftAncestor and rightAncestor:
return root
elif leftAncestor:
return leftAncestor
elif rightAncestor:
return rightAncestor
return None
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
while True:
smaller_value = min(p.val,q.val)
larger_value = max(p.val,q.val)
if root.val < smaller_value:
root = root.right
elif root.val > larger_value:
root = root.left
else:
return root