-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path236_medium_[binary_tree]_lowest_common_ancestor.py
49 lines (36 loc) · 1.36 KB
/
236_medium_[binary_tree]_lowest_common_ancestor.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
# 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(node: TreeNode, path: str, target_node1: TreeNode, target_node2: TreeNode):
if node is None:
return
if node.val == target_node1.val:
target_paths[0] = path
if node.val == target_node2.val:
target_paths[1] = path
dfs(node.left, path + 'l', target_node1, target_node2)
dfs(node.right, path + 'r', target_node1, target_node2)
target_paths = ['', '']
dfs(root, '', p, q)
target_path1 = target_paths[0]
target_path2 = target_paths[1]
common_path = ''
for i in range(min(len(target_path1), len(target_path2))):
if target_path1[i] == target_path2[i]:
common_path += target_path1[i]
else:
break
if len(common_path) == 0:
return root
node = root
for c in common_path:
if c == 'l':
node = node.left
elif c == 'r':
node = node.right
return node