AlgoDaily

Invert a Binary Tree

Read at your own pace. Code execution, quizzes, progress tracking, and the AI tutor are available in the interactive view with JavaScript enabled.

Description

Can you invert a binary tree over its vertical axis? This is a famous problem made popular by this tweet:

Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so f**k off.

— Max Howell (@mxcl) June 10, 2015

Given a binary tree like this:

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

Performing an inversion would result in:

Output:

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

The definition of a tree node is as follows:

function Node(val) {
  this.val = val;
  this.left = null;
  this.right = null;
}
Constraints
  • Number of nodes in the tree <= 1000
  • The nodes will always contain integer values between -1000000000 and 1000000000
  • Expected time complexity : O(n)
  • Expected space complexity : O(logn)
```js
function invertTree(head) {
  return;
};
```

Step Two

This is the famous question that Homebrew author Max Howell famously got wrong in a Google Interview. Hopefully this prevents you from having the same misfortune!

Let's think about brute force-- how would we do it without any clever algorithms? We can start with a very basic input as follows:

  1
 / \
2   3

Step Three

So to invert it vertically, we'd start at 1, where there's nothing to flip or swap, and it would stay put. We've now processed the first row.

Moving on to the second, we encounter 2 and 3, so we'd swap them and get:

  1
 / \
3   2

Step Four

Interesting, this seems to have inverted it! Is it as simple as swapping when there's more than one node?

What if we had more than two nodes to swap per level though? If there was an additional level, it might look like this:

      1
     / \
    3   2
   / \   \
  4   5   3

Step Five

That final row is currently directionally 4 -> 5 -> 3, but we'd want the outcome to be 3 -> 5 -> 4 to be properly inverted.

However, we can achieve this by doing two separate swaps. Notice that the below is what we'd get if we swapped 4 and 5 to obtain 5 -> 4, and then swapping 5 -> 4 with 3.

      1
     / \
    2   3
   /   / \
  3   5   4

Complexity Of Final Solution

So, to put it all together: we can perform an in-order traversal and do a swap at each iteration.

A caveat that was pointed out by readers — if we’re dealing with a substantially large binary tree, then a recursive solution might cause problems due to call stack size. There are two ways to get around this:

  1. Using a stack to mimic the recursion
  2. Using a queue, visiting the levels one by one in a BFS fashion and swapping the left and right nodes to invert the tree.

Here’s what the final code looks like:

function invertTree(head) {
  if (head) {
    var temp = head.left;
    head.left = head.right;
    head.right = temp;

    invertTree(head.left);
    invertTree(head.right);
  }

  return head;
}
Complexity of Final Solution

Let n be the number of nodes in the binary tree. We traverse through all n nodes using recursion for O(n) time complexity, and we can have up to logn recursive calls on the stack at once where logn is the depth of the tree for O(logn) space complexity.

One Pager Cheat Sheet

One Pager Cheat Sheet

  • We can invert a binary tree over its vertical axis, resulting in the reversing of the node values between the left and right subtrees, with a time complexity of O(n) and space complexity of O(logn).
  • Max Howell's misfortune in getting an infamous Google Interview question wrong reminds us to revert to the basics of brute force when confronted with a challenging problem.
  • We swap the key values of successive rows to invert a binary tree vertically.
  • The process of swapping two nodes with more than one node per level could result in the inversion of a binary tree.
  • By swapping 4 and 5, followed by swapping 5 -> 4 and 3, we can get 3 -> 5 -> 4 to correctly invert the binary tree.
  • We can swap the left and right nodes at each iteration by either a recursive stack solution or a queue BFS technique, resulting in an O(n) time and O(logn) space complexity.
Open interactive view →