-
Notifications
You must be signed in to change notification settings - Fork 0
/
236-Lowest_Common_Ancestor_of_a_Binary_Tree.py
72 lines (50 loc) · 1.94 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
64
65
66
67
68
69
70
71
72
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# Recursive Approach
class Solution:
def __init__(self):
self.ans = None
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
pre_dict = collections.defaultdict(list)
q_find, p_find = False, False
def call_pre( node ):
if not node:
return False
left = call_pre( node.left )
right = call_pre(node.right)
# node is one of q or p
mid = node == q or node == p
# from children or one child + itself
if mid + left + right >= 2:
self.ans = node
return mid or left or right
call_pre(root)
return self.ans
class SolutionII:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
pre_dict = collections.defaultdict(list)
q_find, p_find = False, False
def call_pre( pre, node ):
nonlocal q_find, p_find
if not node:
return
if node.val == p.val:
p_find = True
elif node.val == q.val:
q_find = True
pre_dict[node.val].extend( pre + [node] )
if p_find and q_find:
return
call_pre( pre_dict[node.val], node.left )
call_pre( pre_dict[node.val], node.right )
call_pre( [], root )
p_pre = pre_dict[p.val]
q_pre = pre_dict[q.val]
for i in p_pre[::-1]:
for j in q_pre[::-1]:
if i == j:
return i