AlgoDaily

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.

image

Constraints

  • The number of nodes in the tree is in the range [1, 2 * 104].
  • 1 <= Node.val <= 105
  • 1 <= low <= high <= 105
  • All Node.val are unique.

CONTINUE WITH ALGODAILY PREMIUM

Keep going with the complete tutorial.

Unlock the remaining explanations and exercises, alongside the full learning library.

Explore Premium →
Open interactive view →