-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathm1650 v2.py
45 lines (37 loc) · 1.05 KB
/
m1650 v2.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
39
40
41
42
43
44
45
# Optimized version to account for very large graphs since we don't know which one is lower
"""
# Definition for a Node.
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
self.parent = None
"""
class Solution:
def lowestCommonAncestor(self, p: 'Node', q: 'Node') -> 'Node':
visited = set()
while True :
if p and q :
if p in visited :
return p
visited.add(p)
if q in visited :
return q
visited.add(q)
p = p.parent
q = q.parent
elif p :
while p :
if p in visited :
return p
p = p.parent
elif q :
while q :
if q in visited :
return q
q = q.parent
else :
break
return None
return None