-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathinvert_binary_tree.py
64 lines (47 loc) · 1.49 KB
/
invert_binary_tree.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
class TreeNode:
def __init__(self, x):
"""Initialize a tree node object which accepts an integer."""
self.val = x
self.left = None
self.right = None
def invert_tree(node: TreeNode) -> TreeNode:
"""Recursively invert a tree by swapping the right and left nodes.
Initially, the entire tree is accepted as a param, each recursion we go
deeper down the trunk until finally we arrive at the end and go down the
next branch. When there are no more branches, we finally return.
"""
if node is None:
return None
node.left, node.right = node.right, node.left
invert_tree(node.left)
invert_tree(node.right)
return node
def print_tree(node: TreeNode):
"""Print the output of the tree."""
# Print the top level node
print(node.val, end='')
# If other nodes exist, print them too
if node.left:
print_tree(node.left)
if node.right:
print_tree(node.right)
def main() -> TreeNode:
"""Runs the program."""
tree = TreeNode(1)
tree.left = TreeNode(2)
tree.right = TreeNode(3)
tree.left.left = TreeNode(4)
tree.left.right = TreeNode(5)
tree.right.left = TreeNode(6)
tree.right.right = TreeNode(7)
print('Original tree:')
print_tree(tree)
print('')
# Send the entire tree to be inverted
inverted_tree = invert_tree(tree)
print('Inverted tree:')
print_tree(inverted_tree)
print('')
return inverted_tree
if __name__ == '__main__':
main()