DEV Community

Justin Bermudez
Justin Bermudez

Posted on

Invert Binary Tree Python

This is a leetcode question which could be found here

You are given a Binary Tree and you are to invert it or swap every left node with its corresponding right node.

Each BinaryTree node has an integer Value, a Left child node, and Right child node. Children nodes can either be BinaryTree themselves or None/Null.

# Given class definition of a binary tree
# DO NOT TOUCH THIS
class BinaryTree:
    def __init__(self, value):
        self.value = value
        self.left = None
        self.right = None

def invertBinaryTree(tree):
    if tree is None:
        return
    swapLeftAndRight(tree)
    invertBinaryTree(tree.left)
    invertBinaryTree(tree.right)

def swapLeftAndRight(tree):
    tree.left, tree.right = tree.right, tree.left

The swapLeftAndRight function is the most important part where it does the actual swap of the left and right nodes. Python is really nice where you can put a swap onto one line.

Then you would recursively call the invertBinaryTree function to continue swapping the following left and right child nodes.

Discussion (0)