-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path236. Lowest Common Ancestor of a Binary Tree.py
64 lines (50 loc) · 1.56 KB
/
236. Lowest Common Ancestor of a Binary Tree.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# 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.ans = 0
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode',
q: 'TreeNode') -> 'TreeNode':
def reverse(root):
if not root:
return False
left = reverse(root.left)
right = reverse(root.right)
mid = (root == p or root == q)
if mid + left + right >= 2:
self.ans = root
return mid or left or right
reverse(root)
return self.ans
# 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':
stack = []
stack.append(root)
parent = {root: None}
# 将p,q的父节点加入字典
while p not in parent or q not in parent:
node = stack.pop()
if node.left:
stack.append(node.left)
parent[node.left] = node
if node.right:
stack.append(node.right)
parent[node.right] = node
ane = set()
while p:
ane.add(p)
p = parent[p]
while q not in ane:
q = parent[q]
return q