How to Answer: What is the range sum of BST?
Advice and answer examples written specifically for a Javascript Beginner Level Tree job interview.
2. What is the range sum of BST?
This interview question concentrates on the developer's knowledge of JavaScript binary search trees.
You are given the root node of a binary search tree and two integers low and high. Your task is to find the sum of all nodes in the BST which have their values between low and high.
/*Example*/
Given BST-
10
/ \
5 15
/ \ \
3 7 28
low = 7
high = 15
expected output = 32 // (sum of 7, 10, 15)
Solution:
We can traverse over each node of the tree and check if it is in the range. If it is the range, add its value to the result, if not, discard it and iterate over its children. We can use either DFS or BFS to traverse the tree.
class Node {
constructor(val, left, right) {
this.val = val || 0
this.left = left || null
this.right = right || null
}
}
/**
* @param {Node} root
* @param {number} low
* @param {high} low
* @return {number}
*/
function findRangeSum(root, low, high) {
if (root === null) return 0
let result = 0
if (root.val >= low && root.val <= high) {
result += root.val
}
result += rangeSumBST(root.left, low, high)
result += rangeSumBST(root.right, low, high)
return result
}
Time complexity- O(no of nodes)
Space complexity- O(height of tree)
There is one optimization. If the value of a certain node is less than or equal to the low, we need not traverse its left subtree. In the above example, for the node with value 5 which is less than low = 7, we need to traverse its left subtree.
The same is true for high. If the value of a certain node is greater than or equal to the high, we need not traverse its right subtree. In the above example, for the node with value 15 which is greater than or equal to high = 15, we need to traverse its right subtree.
class Node {
constructor(val, left, right) {
this.val = val || 0
this.left = left || 0
this.right = right || 0
}
}
/**
* @param {Node} root
* @param {number} low
* @param {high} low
* @return {number}
*/
function findRangeSum(root, low, high) {
if (root === null) return 0
let result = 0
if (root.val >= low && root.val <= high) {
result += root.val
}
if (root.val > low) {
result += rangeSumBST(root.left, low, high)
}
if (root.val < high) {
result += rangeSumBST(root.right, low, high)
}
return result
}
Time complexity- O(no of nodes)
Space complexity- O(height of tree)
Written by Jennie Taylor on May 21st, 2021