-
Notifications
You must be signed in to change notification settings - Fork 0
/
236.py
47 lines (46 loc) · 1.43 KB
/
236.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
46
47
# 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':
def dfs(root,p,q):
root.parent = None
stack = [root]
self.pq = []
while stack and len(self.pq)<2:
cur = stack.pop()
if cur == p or cur == q:
self.pq.append(cur)
if cur.left:
cur.left.parent = cur
stack.append(cur.left)
if cur.right:
cur.right.parent = cur
stack.append(cur.right)
def findParent(child,parent):
cur = child.parent
while cur:
if cur == parent:
return True
cur = cur.parent
return False
dfs(root,p,q)
if findParent(p,q):
return q
elif findParent(q,p):
return p
else:
seen = set()
cur = self.pq.pop().parent
while cur:
seen.add(cur)
cur = cur.parent
cur = self.pq.pop().parent
while cur:
if cur in seen:
return cur
cur = cur.parent
return None