7
7
"""
8
8
9
9
10
- def binaryTreeMirror (root : int , binary_tree : dict = {}, binary_tree_mirror : dict = {}):
10
+ def binaryTreeMirrorDict (root : int , binary_tree : dict = {}, binary_tree_mirror : dict = {}):
11
+ if root is None or root not in binary_tree .keys ():
12
+ return
13
+ left_child = binary_tree [root ][0 ]
14
+ right_child = binary_tree [root ][1 ]
15
+ binary_tree_mirror [root ] = [right_child , left_child ]
16
+ binaryTreeMirrorDict (left_child , binary_tree , binary_tree_mirror )
17
+ binaryTreeMirrorDict (right_child , binary_tree , binary_tree_mirror )
18
+
19
+ def binaryTreeMirror (root : int , binary_tree : dict = {}) -> dict :
11
20
"""
12
21
>>> binaryTreeMirror(1, { 1: [2,3], 2: [4,5], 3: [6,7], 7: [8,9]})
13
22
{1: [3, 2], 2: [5, 4], 3: [7, 6], 7: [9, 8]}
@@ -17,21 +26,16 @@ def binaryTreeMirror(root: int, binary_tree: dict = {}, binary_tree_mirror: dict
17
26
(1, { 1: [2,3], 2: [4,5], 3: [6,7], 4: [10,11], 5: [12,13],7: [8,9]})
18
27
{1: [3, 2], 2: [5, 4], 4: [11, 10], 5: [13, 12], 3: [7, 6], 7: [9, 8]}
19
28
"""
20
- if root is None or root not in binary_tree .keys ():
21
- return
22
- left_child = binary_tree [root ][0 ]
23
- right_child = binary_tree [root ][1 ]
24
- binary_tree_mirror [root ] = [right_child , left_child ]
25
- binaryTreeMirror (left_child , binary_tree , binary_tree_mirror )
26
- binaryTreeMirror (right_child , binary_tree , binary_tree_mirror )
29
+ binary_tree_mirror = {}
30
+ binaryTreeMirrorDict (root , binary_tree , binary_tree_mirror )
31
+ return binary_tree_mirror
27
32
28
33
29
34
if __name__ == "__main__" :
30
- binary_tree = {1 : [2 , 3 ], 2 : [4 , 5 ], 3 : [6 , 7 ], 7 : [8 , 9 ]}
35
+ binary_tree = { 1 : [2 ,3 ], 2 : [4 ,5 ], 3 : [6 ,7 ], 4 : [ 10 , 11 ], 5 : [ 12 , 13 ], 7 : [8 ,9 ]}
31
36
root = 1
32
37
print ("Binary tree:" , sep = " " )
33
38
print (binary_tree )
34
- binary_tree_mirror = {}
35
- binaryTreeMirror (root , binary_tree , binary_tree_mirror )
39
+ binary_tree_mirror = binaryTreeMirror (root , binary_tree )
36
40
print (" binary tree mirror:" , sep = " " )
37
41
print (binary_tree_mirror )
0 commit comments