938. Range Sum of BST
Easy
Problem:
Transform each node in the BST to the sum of all nodes with values greater than the current node's value.

https://leetcode.com/problems/range-sum-of-bst/
Solution:
Optimization: Pruning
The function dfs uses the properties of a BST to optimize the search. If the current node's value is less than low, then we know that all the values in its left subtree will also be less than low, so we only need to search the right subtree. Conversely, if the current node's value is greater than high, then all the values in its right subtree will also be greater than high, so we only need to search the left subtree.
If the current node's value is less than
low, then the function returns the sum of the values in the right subtree (dfs(node.right)) because all values in the left subtree will be less thanlowand thus out of the desired range.If the current node's value is greater than
high, then the function returns the sum of the values in the left subtree (dfs(node.left)) because all values in the right subtree will be greater thanhighand thus out of the desired range.If the current node's value is within the range
[low, high], then the function returns the sum of the current node's value and the values in both its left and right subtrees (node.val + dfs(node.left) + dfs(node.right)).
Iteration: BFS/DFS
Last updated