← Meta (Facebook) bank

Meta (Facebook) · Question 47 · Trees

Range Sum of BST

TreesPythoncode⏱ O(n)💾 O(h)
Product-based

Problem

You are given BST root and range [low, high]. Find sum of values in range.

Approach

Add in-range values; prune subtrees that cannot contain any.

Time O(n)Space O(h)

How it works

  1. 1Add the node when it falls inside [low, high].
  2. 2Skip the left subtree when node <= low; skip right when node >= high.

Sample input / output

Input:
7 7 15
10 5 15 3 7 x 18
Output:
32

Constraints

1 <= nodes <= 2 * 10^4; 1 <= low <= high <= 10^5.

Solution — read it, then walk it

Time O(n)Space O(h)Loops 1Branches 8Returns 4source · Python
Scroll sideways for wide charts — the view follows the active step.
yesnoyesnoyesnoyesnoyesnoyesnoyesno↻ repeatyesnoSTARTroot, low, highif not rootRETURN 0total = 0if low <= root.val <=hightotal += root.valif root.val > lowtotal +=rangeSumBST(root.left, low,high)if root.val < hightotal +=rangeSumBST(root.right,low, high)RETURN totalCLASS TreeNodeDEFINE __init__(self,val=0, left=None,right=None)self.val = valself.left = leftself.right = rightDEFINE build_tree(values)if not valuesRETURN Noneroot = TreeNode(values[0])queue = [root]i = 1while queue and i <len(values)node = queue.pop(0)if i < len(values) andvalues[i] is not Nonenode.left =TreeNode(values[i])queue.append(node.left)i += 1if i < len(values) andvalues[i] is not Nonenode.right =TreeNode(values[i])queue.append(node.right)i += 1RETURN rootDEFINE main()import sysdata =sys.stdin.read().split()it = iter(data)n = int(next(it)); low =int(next(it)); high =int(next(it))vals = [None if t == 'x'else int(t) for t in[next(it) for _ i…print(rangeSumBST(build_tree(vals),low, high))if __name__ =="__main__"main()END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/43

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits