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 = null;
	this.right = null;
}

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

class BST {
    constructor (value) {
        this.value = value;
        this.left = null;
        this.right = null;
    }
    
    invert () {
        [this.left, this.right] = [this.right, this.left];
        this.left ? this.left.invert() : null;
        this.right ? this.right.invert() : null;
    }
}

ES6 Solution

Copy of Binary Tree Inversion

By Tom Kelly

Copy of Binary Tree Inversion

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

  • 1,210