Skip to content

Instantly share code, notes, and snippets.

@CarlaTeo
Created June 27, 2021 03:32
Show Gist options
  • Save CarlaTeo/d73f40f65b9a1e808dac57a2a8f09642 to your computer and use it in GitHub Desktop.
Save CarlaTeo/d73f40f65b9a1e808dac57a2a8f09642 to your computer and use it in GitHub Desktop.
[JS] BST range sum
function getBSTSum(node, range) {
let sum = 0;
if(!node) return sum;
const [min, max] = range;
if(node.left) sum += getBSTSum(node.left, range);
if(node.val >= min) {
if(node.val <= max) sum += node.val;
else return sum;
}
if(node.right) sum += getBSTSum(node.right, range);
return sum;
}
// ----------------------------------------- Test ----------------------------------------------- //
class Node {
constructor(val) {
this.val = val;
this.left = null;
this.right = null;
}
}
const node2 = new Node(2);
const node3 = new Node(3);
const node4 = new Node(4);
const node5 = new Node(5);
const node6 = new Node(6);
const node7 = new Node(7);
const node8 = new Node(8);
const node9 = new Node(9);
node6.left = node4;
node6.right = node8;
node4.left = node3;
node4.right = node5;
node3.left = node2;
node8.left = node7;
node8.right = node9;
// 6
// / \
// 4 8
// / \ / \
// 3 5 7 9
// /
// 2
console.log(getBSTSum(node6, [3,10])); //42
console.log(getBSTSum(node6, [2,5])); //14
console.log(getBSTSum(node6, [8,9])); //17
console.log(getBSTSum(node6, [4,6])); //15
console.log(getBSTSum(node6, [0,1])); //0
console.log(getBSTSum(node6, [0,11])); //44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment