Range Sum Query in a BST

Problem Given the root of a Binary Search Tree and a range [low, high], return the sum of the values of all nodes whose value falls inside that inclusive range.

Input / Output

  • Input: root of a BST, integers low and high.
  • Output: the integer sum of all in-range node values.

Constraints

  • Up to 10^4 nodes; node values are unique integers.
  • low <= high.
  • The BST invariant holds: everything in a node's left subtree is smaller, everything in the right subtree is larger.

Example

  • Input: root = [10,5,15,3,7,null,18], low = 7, high = 15 -> Output: 32 (7 + 10 + 15).
  • Tricky cases: a range that matches nothing (low = 100, high = 200) -> 0; a range covering everything, which degenerates to a full traversal; and low == high, which reduces to a plain BST lookup.
asked …
LeaderboardSalaryAccount