Created
December 8, 2021 02:41
-
-
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.
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 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