-
Notifications
You must be signed in to change notification settings - Fork 0
/
083.py
65 lines (45 loc) · 989 Bytes
/
083.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
64
65
"""
Problem:
Invert a binary tree.
For example, given the following tree:
a
/ \
b c
/ \ /
d e f
should become:
a
/ \
c b
\ / \
f e d
"""
from DataStructures.Tree import BinaryTree, Node
def invert_helper(node: Node) -> None:
node.right, node.left = node.left, node.right
# recursively inverting the children
if node.right is not None:
invert_helper(node.right)
if node.left is not None:
invert_helper(node.left)
def invert(tree: BinaryTree) -> None:
# inverts the tree in place
if not tree.root:
return
invert_helper(tree.root)
if __name__ == "__main__":
tree = BinaryTree()
tree.root = Node("a")
tree.root.left = Node("b")
tree.root.right = Node("c")
tree.root.left.left = Node("d")
tree.root.left.right = Node("e")
tree.root.right.left = Node("f")
print(tree)
invert(tree)
print(tree)
"""
SPECS:
TIME COMPLEXITY: O(n)
SPACE COMPLEXITY: O(log(n))
"""