Skip to content

Instantly share code, notes, and snippets.

@razniceguy
Created December 8, 2021 02:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save razniceguy/6092a6105e7170776b2f7be4127357d6 to your computer and use it in GitHub Desktop.
Save razniceguy/6092a6105e7170776b2f7be4127357d6 to your computer and use it in GitHub Desktop.
Creates a binary tree from one dimensional array and checks the largest branch from the root recursively.
function getSolution(arr) {
if (Array.isArray(arr)) {
if (arr.length <= 1) {
return '';
} else {
const left = getSumOfBranch(arr, 2);
const right = getSumOfBranch(arr, 3);
return (left === right) ? '' : ((left > right) ? 'Left' : 'Right')
}
} else {
return '';
}
}
function getSumOfBranch(arr, index) {
if (index - 1 < arr.length) {
if (arr[index - 1] === -1) {
return 0;
}
return arr[index - 1]
+ getSumOfBranch(arr, index * 2)
+ getSumOfBranch(arr, index * 2 + 1);
}
return 0;
}
var testArray = [
[[3, 6, 9, -1, 10], 'Left'],
[[1, 4, 100, 5], 'Right'],
[[1, 10, 5, 1, 0, 6], ''],
[[1], ''],
[[], ''],
];
testArray.map((arr, index) => {
var testArr = arr[0];
var solution = arr[1];
var result = getSolution(testArr);
var status = (solution === result) ? 'PASS' : 'FAIL'
solution = (solution === '') ? "''" : solution;
result = (result === '') ? "''" : result;
console.log();
console.log(`Test case ${index}: ${status}`);
console.log(`Expected: ${solution}`);
console.log(`Result: ${result}`);
console.log();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment