Calculating the sum of all nodes in a given range by traversing a Binary Search Tree.
The original problem is here.
BST can be thought of as a sorted array, because in-order traversal of a BST visits the nodes in ascending sorted order.
[low, high].[low, high]. However, this runs in $O(n)$ time regardless of the range as it checks every node.dfs(node).None, there’s no value to add, so return 0.node.val is between low and high (inclusive), we add node.val to our running sum. We then recursively call dfs on both the left and right children, because valid values might exist on both sides.node.val is strictly less than low, we don’t need to search the left subtree anymore because all values there will also be less than low. We simply return the result of dfs on the right child.node.val is strictly greater than high, we don’t need to search the right subtree because those values are even greater. We simply return the result of dfs on the left child.# 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
class Solution:
def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:
if root is None:
return 0
if (root.val < low):
left_sum = 0
else:
left_sum = self.rangeSumBST(root.left, low, high)
if (root.val > high):
right_sum = 0
else:
right_sum = self.rangeSumBST(root.right, low, high)
if (root.val < low) or (root.val > high):
myself = 0
else:
myself = root.val
return myself + left_sum + right_sum
# 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
class Solution:
def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:
if not root:
return 0
# If the value is strictly less than low, skip the left subtree
if root.val < low:
return self.rangeSumBST(root.right, low, high)
# If the value is strictly greater than high, skip the right subtree
if root.val > high:
return self.rangeSumBST(root.left, low, high)
# If it is in range, include the node and check both subtrees
return root.val + \
self.rangeSumBST(root.left, low, high) + \
self.rangeSumBST(root.right, low, high)
[low, high]. On average, however, the time complexity will be much better than $O(n)$ because the BST property allows us to prune many branches.