DEV Community

Justin Bermudez
Justin Bermudez

Posted on

2 2

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.

AWS Q Developer image

Your AI Code Assistant

Generate and update README files, create data-flow diagrams, and keep your project fully documented. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay