oneby7

Binary Search Trees BST basics

385. Range Sum of BST

Easy

You are given root, the root node of a binary search tree, and two integers low and high. Return the sum of the values of all nodes whose value lies between low and high, both included. If no value lies in that range, return 0.

In a binary search tree, every value in a node's left subtree is smaller than the node's value, and every value in its right subtree is larger. The values in the tree are distinct.

The examples write a tree level by level, from left to right, with null where a child is missing. So root = [5,8,null,3] is the root 5 with a left child 8 and no right child, and 8 has a left child 3. The missing children after the last node are left out.

Example 1

46911132027303450

Input: root = [20, 9, 34, 4, 13, 27, 50, null, 6, 11, null, null, 30] low = 11 high = 30

Output: 101

Explanation: The nodes 11, 13, 20, 27 and 30 lie in the range, and 11 + 13 + 20 + 27 + 30 = 101. The values 11 and 30 sit exactly on the bounds, and they count.

Example 2

-12-7-538

Input: root = [-5, -12, 8, null, -7, 3] low = -10 high = 2

Output: -12

Explanation: Only -7 and -5 lie in the range, so the sum is -12. The value -12 is below low, and 3 and 8 are above high.

Example 3

99999999799999999899999999910⁹

Input: root = [999999999, 999999998, 1000000000, 999999997] low = -1000000000 high = 1000000000

Output: 3999999994

Explanation: Every node lies in the range, so the answer is the sum of all four values.

Check your understanding

Work out the answer for this input before you write any code.

root = [15, 7, 22, 3, 10, 18, 30] low = 7 high = 18

Constraints

  • 1 ≤ number of nodes ≤ 105
  • -109 ≤ Node.val ≤ 109
  • The tree has at most 1000 levels.
  • The tree is a binary search tree, and its values are distinct.
  • -109 ≤ low ≤ high ≤ 109

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.