Skip to content

Instantly share code, notes, and snippets.

@gcagle3
Last active October 26, 2021 16:28
Show Gist options
  • Save gcagle3/130f24b9ccc6ab543b12125dbe3b1f0b to your computer and use it in GitHub Desktop.
Save gcagle3/130f24b9ccc6ab543b12125dbe3b1f0b to your computer and use it in GitHub Desktop.
Inverting Binary Tree in Python
#!/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