Skip to content

Instantly share code, notes, and snippets.

@sofish
Created June 11, 2015 05:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save sofish/10e0084dea4b76ec45f4 to your computer and use it in GitHub Desktop.
Save sofish/10e0084dea4b76ec45f4 to your computer and use it in GitHub Desktop.
invert binary tree
function invert(tree) {
if (!tree instanceof Array || tree.length === 1) return tree;
var ret = [];
var inverted = tree.reverse();
for(var cur in inverted) {
if(!inverted.hasOwnProperty(cur)) continue;
ret.push(inverted[cur] instanceof Array ? invert(inverted[cur]) : inverted[cur]);
}
return ret;
}
var tree = [[['a'], 'b', ['c', 'd', null]], 'f', [['g'], 'h', ['i']]];
console.log(invert(tree));
// [ [ [ 'i' ], 'h', [ 'g' ] ], 'f', [ [ null, 'd', 'c' ], 'b', [ 'a' ] ] ]
'use strict';
function invert(tree) {
if (!tree instanceof Array || tree.length === 1) return tree;
return tree.reverse().map(function (cur) {
return Array.isArray(cur) ? invert(cur) : cur;
});
}
var tree = [[['a'], 'b', ['c', 'd', null]], 'f', [['g'], 'h', ['i']]];
console.log(invert(tree));
// [ [ [ 'i' ], 'h', [ 'g' ] ], 'f', [ [ null, 'd', 'c' ], 'b', [ 'a' ] ] ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment