|
8 | 8 | from test_framework.test_utils import enable_executor_hook
|
9 | 9 |
|
10 | 10 |
|
| 11 | +def get_path(root, node, path): |
| 12 | + if not root: |
| 13 | + return False |
| 14 | + path.append(root) |
| 15 | + if root == node: |
| 16 | + return True |
| 17 | + |
| 18 | + if root.left: |
| 19 | + if get_path(root.left, node, path): |
| 20 | + return True |
| 21 | + if root.right: |
| 22 | + if get_path(root.right, node, path): |
| 23 | + return True |
| 24 | + path.pop() |
| 25 | + return False |
| 26 | + |
| 27 | + |
| 28 | +def lca_Oh_space(tree: BinaryTreeNode, node0: BinaryTreeNode, |
| 29 | + node1: BinaryTreeNode) -> Optional[BinaryTreeNode]: |
| 30 | + node0_path = [] |
| 31 | + get_path(tree, node0, node0_path) |
| 32 | + node1_path = [] |
| 33 | + get_path(tree, node1, node1_path) |
| 34 | + |
| 35 | + solution = tree |
| 36 | + for n0, n1 in zip(node0_path, node1_path): |
| 37 | + if n0 is n1: |
| 38 | + solution = n0 |
| 39 | + else: |
| 40 | + break |
| 41 | + |
| 42 | + return solution |
| 43 | + |
| 44 | + |
11 | 45 | def lca(tree: BinaryTreeNode, node0: BinaryTreeNode,
|
12 | 46 | node1: BinaryTreeNode) -> Optional[BinaryTreeNode]:
|
13 |
| - # TODO - you fill in here. |
14 |
| - return None |
| 47 | + best_lca = tree |
| 48 | + best_lca_distance = 0 |
| 49 | + |
| 50 | + def nodes_in_tree(root, depth): |
| 51 | + if not root: |
| 52 | + return False, False |
| 53 | + |
| 54 | + node0_left, node1_left = nodes_in_tree(root.left, depth+1) |
| 55 | + node0_right, node1_right = nodes_in_tree(root.right, depth+1) |
| 56 | + |
| 57 | + node0_exists = (root is node0) or node0_left or node0_right |
| 58 | + node1_exists = (root is node1) or node1_left or node1_right |
| 59 | + |
| 60 | + nonlocal best_lca_distance |
| 61 | + nonlocal best_lca |
| 62 | + if (node0_exists and node1_exists) and best_lca_distance < depth: |
| 63 | + best_lca_distance = depth |
| 64 | + best_lca = root |
| 65 | + |
| 66 | + return node0_exists, node1_exists |
| 67 | + |
| 68 | + node0_exists, node1_exists = nodes_in_tree(tree, 0) |
| 69 | + |
| 70 | + return best_lca if (node0_exists and node1_exists) else None |
15 | 71 |
|
16 | 72 |
|
17 | 73 | @enable_executor_hook
|
|
0 commit comments