VOOZH about

URL: https://www.geeksforgeeks.org/dsa/sum-of-nodes-in-a-binary-search-tree-with-values-from-a-given-range/

⇱ Sum of BST Nodes Within a Given Range - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sum of BST Nodes Within a Given Range

Last Updated : 11 Oct, 2025

Given the root of a Binary Search Tree containing n nodes, and two integers l and r, find the sum of all node values that lie within the inclusive range [l, r].

Examples:

Input: l = 10, r = 22

👁 print_bst_keys_in_given_range

Output: 54
Explanation: The nodes in the given Tree that lies in the range [10, 22] are {12, 20, 22}. Therefore, the sum of nodes is 12 + 20 + 22 = 54.

Input: l = 11, r = 15

👁 420046700

Output: 11
Explanation: The nodes in the given Tree that lies in the range [11, 15] is {11}. Therefore, the sum of node is 11.

[Approach] - Traverse the tree and check if node lies in range

The idea to traverse the tree recursively. For each node, if it lies within the range, then return the sum of left subtree, right subtree and current node. If its value is less than range, then return the value of right subtree, because all the nodes in its left subtree are less than than the range. Otherwise return the value of left subtree, because all the nodes in its right subtree are greater than the range.


Output
54

Time Complexity: O(n), where n is the number of nodes in tree.
Auxiliary Space: O(h), where h is the height of tree.

Related articles:

Comment