-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy path055_lowestCommonAncestor.py
More file actions
34 lines (29 loc) · 973 Bytes
/
055_lowestCommonAncestor.py
File metadata and controls
34 lines (29 loc) · 973 Bytes
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
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def __init__(self):
self.ancestor = None
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
def _helper(root, low, high):
if root == None:
return None
if low <= root.val <= high:
self.ancestor = root
return
elif high > root.val:
right = _helper(root.right, low, high)
elif low < root.val:
left = _helper(root.left, low, high)
high = low = 0
if p.val > q.val:
high = p.val
low = q.val
else:
high = q.val
low = p.val
_helper(root, low, high)
return self.ancestor