-
-
Save tfirdaus/6109c5606c77c87e4a44bf36b983fecf 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