Created
April 6, 2023 00:03
-
-
Save TiagoFuelber/18b81f8d9ab06af88ca8837455f45298 to your computer and use it in GitHub Desktop.
Which branch of the tree is bigger?
This file contains 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 compareBranches(arr) { | |
// Helper function to traverse the tree recursively | |
function sum(node) { | |
if (!node) { | |
return 0; | |
} | |
return node + sum(arr.shift() && arr.shift() ? node * 2 : null) + sum(arr.shift() && arr.shift() ? node * 2 + 1 : null); | |
} | |
const leftSum = sum(arr.shift()); | |
const rightSum = sum(arr.shift()); | |
if (leftSum > rightSum) { | |
return "Left"; | |
} else if (rightSum > leftSum) { | |
return "Right"; | |
} else { | |
return ""; | |
} | |
} | |
// test cases | |
/** | |
Input: arr: [3, 6, 2, 9, -1, 10] | |
Expected Output: "Left" | |
Input: arr: [1, 4, 100, 5] | |
Expected Output: "Right" | |
Equal branches | |
Input: arr: [1, 10, 5, 1, 0, 6] | |
Expected Output: "" | |
Empty tree | |
Input: arr: [] | |
Expected Output: "" | |
Only root branch | |
Input: arr: [1] | |
Expected Output: "" | |
*/ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment