-
Notifications
You must be signed in to change notification settings - Fork 3
/
q0235.py
38 lines (33 loc) · 930 Bytes
/
q0235.py
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
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':
left = [None]
right = [None]
tmp = root
while tmp != p:
left.append(tmp)
if tmp.val < p.val:
tmp = tmp.right
else:
tmp = tmp.left
left.append(tmp)
tmp = root
while tmp != q:
right.append(tmp)
if tmp.val < q.val:
tmp = tmp.right
else:
tmp = tmp.left
right.append(tmp)
result = None
length = min(len(left), len(right))
for i in range(length):
if left[i] == right[i]:
result = left[i]
else:
break
return result