992. Range Sum in BSTPOTD

Given a root of binary search tree and two integers low, high. Return the sum of all elements that lie in inclusive range of [low, high].

Example 1:

Input : root = 5 2 7 1 3 null 10 , low = 3, high = 7

Output : 15

Explanation : The element 3, 5, 7 lies in range [3, 7]. The sum is 3 + 5 + 7 -> 15.

Example 2:

Input : root = 15 12 17 11 13 null 10 , low = 3, high = 7

Output : 0

Explanation : No element lies in the range [3,7], so the sum is 0.

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= Number of Nodes <= 104
  • 1 <= nodes value <= 105

Fun Facts

0
/**
* Definition for a binary tree node.
* struct TreeNode {
* int data;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int val) : data(val) , left(nullptr) , right(nullptr) {}
* };
**/
 
class Solution{
public:
int rangeSumBST(TreeNode* root, int low, int high){
//your code goes here
}
};
Test Case

Input:

High
Low
Root