Branch sum
Find Closest Value in BTS
// This is the class of the input root.
// Do not edit it.
class BinaryTree {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
// O(n) time | O(n) space - where n is number of node
function branchSums(root) {
const sums = [];
branchSumHelper(root, 0, sums);
return sums;
}
function branchSumHelper(node, runningSum, sums) {
if (!node) return;
const newRunningSum = runningSum + node.value;
// No more left or right node
if (!node.left && !node.right) {
sums.push(newRunningSum);
return;
}
branchSumHelper(node.left, newRunningSum, sums);
branchSumHelper(node.right, newRunningSum, sums);
}
// Do not edit the lines below.
exports.BinaryTree = BinaryTree;
exports.branchSums = branchSums;
Last updated