Skip to content

Instantly share code, notes, and snippets.

@TiagoFuelber
Created April 6, 2023 00:03
Show Gist options
  • Save TiagoFuelber/18b81f8d9ab06af88ca8837455f45298 to your computer and use it in GitHub Desktop.
Save TiagoFuelber/18b81f8d9ab06af88ca8837455f45298 to your computer and use it in GitHub Desktop.
Which branch of the tree is bigger?
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