v9.1.1
Menu

Range Sum of BST

easyPROTrees & BFS/DFSMeta DSA

Given the root of a BST (as a level-order array) and two integers low and high, return the sum of all node values in the inclusive range [low, high].

Example

Input
10,5,15,3,7,null,18
7
15
Output
32
Reasoning
  • The given level-order array represents a Binary Search Tree (BST) with the following structure:
    • Root: 10
    • Left child: 5
    • Right child: 15
    • Left grandchild of root: 3 (left child of 5)
    • Right grandchild of root: 7 (right child of 5)
    • Right grandchild of root: 18 (right child of 15)
  • We traverse the BST and consider node values within the range [7,15][7, 15]
  • The node values within this range are 7, 10, and 15, so we calculate the sum: 7+10+15=327 + 10 + 15 = 32
  • The final output is the sum of these node values, which is 32

Constraints

  • 1 <= number of nodes <= 2 * 10^4
  • 1 <= Node.val <= 10^5
  • 1 <= low <= high <= 10^5

Learn this in

More from Meta DSA

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.