-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
82 lines (66 loc) · 2.06 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// 101.js
// node index.js
// npm test
// warming up before your test
// challenge question:
// Given a binary tree represented as an array,
// write a function that calculates the sum of the left branch and the sum of the right branch, and returns the largest branch as a string.
// If the left branch is larger, return 'Left'
// If the right branch is larger, return 'Right'
// If they are equal, return 0
// If the tree has 0 nodes, return 0
// -1 is a non-existent node
let arr = [3, 6, 2, 9, -1, 10]; // Left
// let arr = [1, 4, 100, 5]; // Right
// let arr = [1, 10, 5, 1, 12, 6]; // Equal
// let arr = []; // Empty tree
// let arr = [7]; // Only root node
const solution = (arr) => {
// Type your solution here
console.log(arr);
function filterArr(arr) {
// Remove root node
arr.shift();
// Remove all non-existent nodes (-1)
return arr.filter((node) => node !== -1);
}
function leftBranchSum(arr) {
let sum = 0;
for (let i = 0; i < arr.length; i += 2) {
sum += arr[i];
}
return sum;
}
function rightBranchSum(arr) {
let sum = 0;
for (let i = 1; i < arr.length; i += 2) {
sum += arr[i];
}
return sum;
}
// filterArr(arr);
arr = filterArr(arr);
console.log("Filtered Array: ", arr);
let leftSum = leftBranchSum(arr);
let rightSum = rightBranchSum(arr);
console.log("Left Branch Sum", leftSum);
console.log("Right Branch Sum", rightSum);
function calcLrgstBranch(arr, leftSum, rightSum) {
let res = null;
if (leftSum > rightSum) {
res = "Left";
} else if (leftSum < rightSum) {
res = "Right";
} else if (leftSum === rightSum && arr.length > 1) {
res = "Equal";
} else if (arr.length == 0 || arr.length == 1) {
res = 0;
}
return res;
}
let result = calcLrgstBranch(arr, leftSum, rightSum);
console.log("Result:", result);
return result;
};
solution(arr);
module.exports = solution;