R

E

A

C

T

O

xamples 

epeat

ode

pproach

ptimize

est

{Binary Tree Inversion}

The Question

Invert a binary tree about its y-axis.

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**k off.

Example

4

2

7

1

3

6

9

4

7

2

9

6

3

1

Invert this tree

Into this tree

Example

Assume a `BinarySearchTree` constructor function is already created for you

function BinarySearchTree(value){
	this.value = value;
	this.left = undefined;
	this.right = undefined;
}

You need to create an inverse method for this `BinarySearchTree` that when invoked `BinarySearchTree.inverse()`, will inverse the tree

BinarySearchTree.prototype.inverse = function(){
	(function inverseFunc(tree){
		var temp = tree.left;
		tree.left = tree.right;
		tree.right = temp;
		if(tree.left) inverseFunc(tree.left);
		if(tree.right) inverseFunc(tree.right);
	})(this);
};

Solution

Binary Tree Inversion

By pat310

Binary Tree Inversion

Technical interview problem to invert a binary tree about its y-axis

  • 1,985