Invert Binary Tree Python
Justin Bermudez
Posted on September 27, 2020
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.
đź’– đź’Ş đź™… đźš©
Justin Bermudez
Posted on September 27, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
algorithms How to Code the Greatest Common Divisor Algorithm in JavaScript and Python
January 27, 2023