Given the root of a Binary Search Tree (BST) and two integers low
and high
, return the sum of the values of all nodes with a value in the inclusive range [low, high]
.
root = [10, 5, 15, 3, 7, null, 18]
, low = 7
, high = 15
32
root = [10, 5, 15, 3, 7, 13, 18, 1, null, 6]
, low = 6
, high = 10
23
low
and high
always within the range of node values?
low
and high
are integers, and they are used to find nodes within a specified range.Given that it’s a BST, properties like the left subtree having smaller values and the right subtree having larger values can be leveraged to efficiently navigate the tree:
Traversal Approach: An In-Order DFS (Depth-First Search) will ensure visiting nodes in non-decreasing order.
low
, skip the left subtree because all values there will also be less than low
.high
, skip the right subtree because all values there will also be greater than high
.[low, high]
, add it to the sum.low
and high
.# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def rangeSumBST(root: TreeNode, low: int, high: int) -> int:
def dfs(node: TreeNode) -> int:
if not node:
return 0
if node.val < low:
# Only right subtree could have nodes in range
return dfs(node.right)
elif node.val > high:
# Only left subtree could have nodes in range
return dfs(node.left)
else:
# Current node is in range, check both subtrees
return node.val + dfs(node.left) + dfs(node.right)
return dfs(root)
[low, high]
.This time complexity is efficient given the properties of the BST and the constraints of the problem.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?