Skip to content

Instantly share code, notes, and snippets.

@nickleefly nickleefly/invert.js
Last active Jun 20, 2017

Embed
What would you like to do?
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' ] ] ]
function isSymmetric(root) {
return isSymmetricHelper(root.left, root.right);
}
function isSymmetricHelper(t1, t2) {
if (t1 == null && t2 == null) {
return true;
}
if (t1 == null || t2 == null) {
return false;
}
return isSymmetricHelper(t1.left, t2.right) &&
isSymmetricHelper(t1.right, t2.left);
}
function isSymmetric(root) {
return isEqual(reverse(root.left), root.right);
}
function reverse(t) {
var tmp = t.left;
t.left = reverse(t.right);
t.right = reverse(tmp);
return t;
}
function isEqual(t1, t2) {
if (t1 == null && t2 == null) {
return true;
}
if (t1 == null || t2 == null) {
return false;
}
return isEqual(t1.left, t2.left) && isEqual(t1.right, t2.right);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.