|
1 |
| -# Created by susmith98 |
2 |
| - |
3 |
| - |
4 | 1 | """
|
5 | 2 | Problem Description:
|
6 | 3 | Given a binary tree, return it's mirror.
|
7 | 4 | """
|
8 | 5 |
|
9 | 6 |
|
10 |
| -def binary_tree_mirror_dict(root: int, binary_tree_mirror_dictionary: dict): |
| 7 | +def binary_tree_mirror_dict(binary_tree_mirror_dictionary: dict, root: int): |
11 | 8 | if not root or root not in binary_tree_mirror_dictionary:
|
12 | 9 | return
|
13 |
| - left_child = binary_tree_mirror_dictionary[root][0] |
14 |
| - right_child = binary_tree_mirror_dictionary[root][1] |
| 10 | + left_child, right_child = binary_tree_mirror_dictionary[root][:2] |
15 | 11 | binary_tree_mirror_dictionary[root] = [right_child, left_child]
|
16 |
| - binary_tree_mirror_dict(left_child, binary_tree_mirror_dictionary) |
17 |
| - binary_tree_mirror_dict(right_child, binary_tree_mirror_dictionary) |
| 12 | + binary_tree_mirror_dict(binary_tree_mirror_dictionary, left_child) |
| 13 | + binary_tree_mirror_dict(binary_tree_mirror_dictionary, right_child) |
18 | 14 |
|
19 | 15 |
|
20 |
| -def binary_tree_mirror(binary_tree: dict = {}, root: int = 1) -> dict: |
| 16 | +def binary_tree_mirror(binary_tree: dict, root: int = 1) -> dict: |
21 | 17 | """
|
22 | 18 | >>> binary_tree_mirror({ 1: [2,3], 2: [4,5], 3: [6,7], 7: [8,9]}, 1)
|
23 | 19 | {1: [3, 2], 2: [5, 4], 3: [7, 6], 7: [9, 8]}
|
24 | 20 | >>> binary_tree_mirror({ 1: [2,3], 2: [4,5], 3: [6,7], 4: [10,11]}, 1)
|
25 | 21 | {1: [3, 2], 2: [5, 4], 3: [7, 6], 4: [11, 10]}
|
| 22 | + >>> binary_tree_mirror({ 1: [2,3], 2: [4,5], 3: [6,7], 4: [10,11]}, 5) |
| 23 | + Traceback (most recent call last): |
| 24 | + ... |
| 25 | + ValueError: binary tree cannot be empty |
| 26 | + >>> binary_tree_mirror({}, 5) |
| 27 | + Traceback (most recent call last): |
| 28 | + ... |
| 29 | + ValueError: root 5 is not present in the binary_tree |
26 | 30 | """
|
27 | 31 | if not binary_tree:
|
28 | 32 | raise ValueError("binary tree cannot be empty")
|
29 | 33 | if root not in binary_tree:
|
30 |
| - raise ValueError("root is present in the binary_tree") |
| 34 | + raise ValueError(f"root {root} is not present in the binary_tree") |
31 | 35 | binary_tree_mirror_dictionary = dict(binary_tree)
|
32 |
| - binary_tree_mirror_dict(root, binary_tree_mirror_dictionary) |
| 36 | + binary_tree_mirror_dict(binary_tree_mirror_dictionary, root) |
33 | 37 | return binary_tree_mirror_dictionary
|
34 | 38 |
|
35 | 39 |
|
36 | 40 | if __name__ == "__main__":
|
37 | 41 | binary_tree = {1: [2, 3], 2: [4, 5], 3: [6, 7], 7: [8, 9]}
|
38 |
| - print("Binary tree: ", binary_tree) |
39 |
| - binary_tree_mirror_dictionary = binary_tree_mirror(binary_tree, 1) |
40 |
| - print("Binary tree mirror: ", binary_tree_mirror_dictionary) |
| 42 | + print(f"Binary tree: {binary_tree}") |
| 43 | + binary_tree_mirror_dictionary = binary_tree_mirror(binary_tree, 5) |
| 44 | + print(f"Binary tree mirror: {binary_tree_mirror_dictionary}") |
0 commit comments