Created
June 11, 2015 05:43
-
-
Save sofish/10e0084dea4b76ec45f4 to your computer and use it in GitHub Desktop.
invert binary tree
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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' ] ] ] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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