Last active
October 26, 2021 16:28
-
-
Save gcagle3/130f24b9ccc6ab543b12125dbe3b1f0b to your computer and use it in GitHub Desktop.
Inverting Binary Tree in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
class Node(): | |
""" | |
Node class used to build a binary tree | |
""" | |
def __init__(self, val): | |
self.val = val | |
self.left = None | |
self.right = None | |
def printTree(node): | |
""" | |
printTree takes a binary tree (of class Node) and prints it recursively | |
""" | |
print(node.val) | |
if node.left != None: | |
printTree(node.left) | |
if node.right != None: | |
printTree(node.right) | |
def invertBinaryTree(node): | |
""" | |
invertBinaryTree takes a binary tree (of class Node) and inverts it, returning a new inverted binary tree | |
""" | |
if node == None: | |
return None | |
node.left, node.right = node.right, node.left | |
invertBinaryTree(node.left) | |
invertBinaryTree(node.right) | |
return node | |
# Initialize tree | |
tree = Node(1) | |
tree.left = Node(2) | |
tree.right = Node(3) | |
tree.left.left = Node(4) | |
tree.left.right = Node(5) | |
tree.right.left = Node(6) | |
tree.right.right = Node(7) | |
print("Original tree:\n") | |
printTree(tree) | |
invTree = invertBinaryTree(tree) | |
print("\nInverted tree:\n") | |
printTree(invTree) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment