Sum Nodes Within Range for a Binary Search Tree
Read at your own pace. Code execution, quizzes, progress tracking, and the AI tutor are available in the interactive view with JavaScript enabled.
Question
A binary search tree is a data structure that has the following properties,
- Each node in the tree has only two children.
- The left subtree consists of nodes with values less than the root node.
- The right subtree consists of nodes with values greater than the root node.
Consider that you are given a binary search tree as root, and two integers low and high. Can you find the sum of values of all nodes that are in the inclusive range [low, high]?
This problem can be best understood visually. Consider the example below. Nodes with values between the [7, 15] range are colored orange, and the sum of values of these nodes gives us the answer.

Constraints
- The number of nodes in the tree is in the range [1, 2 * 104].
1 <= Node.val <= 1051 <= low <= high <= 105- All
Node.valare unique.
CONTINUE WITH ALGODAILY PREMIUM
Keep going with the complete tutorial.
Unlock the remaining explanations and exercises, alongside the full learning library.
Explore Premium →