-
Notifications
You must be signed in to change notification settings - Fork 0
/
lowest_common_ancestor_binary_tree.py
63 lines (51 loc) · 1.65 KB
/
lowest_common_ancestor_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, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
def dfs(curr, node, path):
if not curr:
return False
if curr == node:
return path
if ans := dfs(curr.left, node, path + [curr.left]):
return ans
return dfs(curr.right, node, path + [curr.right])
path_p = dfs(root, p, [root])
path_q = dfs(root, q, [root])
n = len(path_p)
m = len(path_q)
ptr = 1
while True:
if ptr >= n or ptr >= m or path_p[ptr] != path_q[ptr]:
return path_p[ptr - 1]
ptr += 1
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if not root:
return False
if root == p or root == q:
return root
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)
if left and right:
return root
if left:
return left
return right
# root = TreeNode(3)
# p = root.left = TreeNode(5)
# root.right = TreeNode(1)
#
# root.left.left = TreeNode(6)
# root.left.right = TreeNode(2)
#
# root.right.left = TreeNode(0)
# root.right.right = TreeNode(8)
#
# root.left.right.left = TreeNode(7)
# q = root.left.right.right = TreeNode(4)
# print(Solution().lowestCommonAncestor(root, p, q))