Skip to content

Instantly share code, notes, and snippets.

@kidGodzilla
Created May 28, 2016 19:42
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save kidGodzilla/9a834f6f531a95000587cc9d244f2b1a to your computer and use it in GitHub Desktop.
Save kidGodzilla/9a834f6f531a95000587cc9d244f2b1a to your computer and use it in GitHub Desktop.
Invert a Binary Tree in Javascript
// 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 fuck off.
// So, let's invert a binary tree in Javascript
// Original Tree
// 4
// / \
// 2 7
// / \ / \
// 1 3 6 9
// Simple Binary Tree (depth = 3)
var tree = {
left: {
left: {
value: 1
},
right: {
value: 3
},
value: 2
},
right: {
left: {
value: 6
},
right: {
value: 9
},
value: 7
},
value: 4
}
// Recursive function to return an inverted tree
function invertTree (node) {
if (!node) return;
var right = invertTree(node.right);
var left = invertTree(node.left);
if (left) node.left = right;
if (right) node.right = left;
return node;
}
// Inverted Tree
// 4
// / \
// 7 2
// / \ / \
// 9 6 3 1
// Log the original tree to the console, followed by the inverted tree
console.log(JSON.parse(JSON.stringify(tree)), invertTree(tree));
@lrgalego
Copy link

lrgalego commented Oct 31, 2017

If the tree is not balanced your code will fail to invert it.
Example, try to run it with this tree:
tree = { left: null, right: { left: { value: 6 }, right: { value: 9 }, value: 7 }, value: 4 }

@dalvallana
Copy link

No need to ask if (left) and if (right) in lines 42 and 43, just set the values (even if they're null or undefined). That way unbalanced trees will work as well.

@GiridharSundar
Copy link

GiridharSundar commented Mar 13, 2021

var invertTree = function(root) {
    if(!root)
        return root
    var left = invertTree(root.left)
    var right = invertTree(root.right)
    root.left = left === undefined ? null : right;
    root.right = right === undefined ? null : left;
    return root
};

This code works for all types of trees

@Evand3r
Copy link

Evand3r commented Apr 4, 2022

My implementantion:

function invertTree(node) {
  if(node) {
    [node.left, node.right] = [node.right, node.left];
    
    invertTree(node.left);
    invertTree(node.right);
  }

  return node;
}

@dante4rt
Copy link

dante4rt commented Aug 9, 2023

This is my way :

function invertTree(node) {
  if (!node) {
    return null;
  }

  const { left, right } = node;

  node.left = invertTree(right);
  node.right = invertTree(left);

  return node;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment