Teaching Kids Programming – Recursive Algorithm to Invert a Binary Tree


Teaching Kids Programming: Videos on Data Structures and Algorithms

This problem was inspired by this original tweet by Max Howell:
Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so f*** off.

invert-a-binary-tree Teaching Kids Programming - Recursive Algorithm to Invert a Binary Tree algorithms python teaching kids programming youtube video

Invert a binary tree.
Example:

Input:

     4
   /   \
  2     7
 / \   / \
1   3 6   9

Output:

     4
   /   \
  7     2
 / \   / \
9   6 3   1

Invert a Binary Tree by Recursive Algorithm

Recursion is a powerful tool and by using it, we can invert a binary tree in a trivial manner. The terminal case is to invert a None node which is None, then, we just have to recursively invert left and right subtrees, and assign the results to the right and left pointers.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def invertTree(self, root: TreeNode) -> TreeNode:
        if root is None:
            return None
        left = self.invertTree(root.left)
        right = self.invertTree(root.right)
        root.left = right
        root.right = left
        return root
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def invertTree(self, root: TreeNode) -> TreeNode:
        if root is None:
            return None
        left = self.invertTree(root.left)
        right = self.invertTree(root.right)
        root.left = right
        root.right = left
        return root

The complexity is O(N) where N is the number of the nodes in the binary tree. Using recursion gives O(N) space usage.

See also other posts on inverting the binary tree:

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
456 words
Last Post: Algorithms to Count the Equivalent Pairs in an Array
Next Post: Depth First Search Algorithm to Perform Phone Number Permutations

The Permanent URL is: Teaching Kids Programming – Recursive Algorithm to Invert a Binary Tree

Leave a Reply