Created
January 13, 2019 19:41
-
-
Save j-quelly/1b70dbf9cfb8488125424d40fa1689d8 to your computer and use it in GitHub Desktop.
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 get(object, prop, notFound = undefined) { | |
if (object) { | |
if (prop in object) { | |
return object[prop]; | |
} | |
} | |
return notFound; | |
} | |
function depthFirst(tree, order, isNotSymmetrical, callback) { | |
const value = get(tree, 'value'); | |
const left = get(tree, 'left'); | |
const right = get(tree, 'right'); | |
if (right && !left) { | |
// console.log('is not symmetrical') | |
isNotSymmetrical = true; | |
// callback(value, true) | |
} | |
if (left && !right) { | |
isNotSymmetrical = true; | |
} | |
order === "pre" && callback(value, isNotSymmetrical); | |
left && depthFirst(left, order, isNotSymmetrical, callback); | |
order === "in" && callback(value, isNotSymmetrical); | |
right && depthFirst(right, order, isNotSymmetrical, callback); | |
order === "post" && callback(value, isNotSymmetrical); | |
} | |
function isTreeSymmetric(t) { | |
let isNotSymmetrical = false; | |
const _in = []; | |
depthFirst(t, 'in', isNotSymmetrical, (val, notSymm = false) => { | |
if (notSymm) { | |
isNotSymmetrical = notSymm; | |
} | |
_in.push(val); | |
}); | |
if (isNotSymmetrical) { | |
// return false; | |
} | |
// in | |
if (_in.length % 2 === 1) { | |
const arrLen = (_in.length - 1) / 2; | |
const left = _in.splice(0, arrLen); | |
_in.splice(0,1); | |
const right = _in.reverse(); | |
return left.every((int, index) => { | |
return int === right[index]; | |
}) | |
} | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment