Invert a Binary Tree (Hard)

Good morning! Here's our prompt for today.

You may see this problem at Flipkart, Oracle, Zillow, Snap, Intercom, Databricks, Twilio, Red Hat, Ibm, Lucid Software, Keeptruckin, Servicenow, Docusign, Sonos, and Electronic Arts.

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
Description

Given a binary tree like this:

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

Performing an inversion would result in:

SNIPPET
1Output:
2
3     4
4   /   \
5  7     2
6 / \   / \
79   6 3   1

The definition of a tree node is as follows:

JAVASCRIPT
1function Node(val) {
2  this.val = val;
3  this.left = null;
4  this.right = null;
5}

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)
JAVASCRIPT
OUTPUT
Results will appear here.