Range Sum of BST — BST Property Pruning DFS

Sanjeev SharmaSanjeev Sharma
1 min read

Advertisement

Problem 357 · Range Sum of BST

Difficulty: Easy · Pattern: BST Pruning DFS

Solutions

# Python
def rangeSumBST(root, low, high):
    if not root: return 0
    total = root.val if low <= root.val <= high else 0
    if root.val > low: total += rangeSumBST(root.left, low, high)
    if root.val < high: total += rangeSumBST(root.right, low, high)
    return total
// Java
public int rangeSumBST(TreeNode root, int low, int high) {
    if (root==null) return 0;
    int sum = (root.val>=low&&root.val<=high)?root.val:0;
    if (root.val>low) sum+=rangeSumBST(root.left,low,high);
    if (root.val<high) sum+=rangeSumBST(root.right,low,high);
    return sum;
}

Complexity

  • Time: O(n) worst, O(log n + k) with pruning (k = elements in range)
  • Space: O(h)

Advertisement

Sanjeev Sharma

Written by

Sanjeev Sharma

Full Stack Engineer · E-mopro