Sponsored
Sponsored
This approach involves performing a recursive in-order traversal to accumulate the sum of nodes within the given value range.
Because of the BST properties, the in-order traversal naturally allows visiting nodes in a sorted order, which means that once the current node value is larger than 'high', you can stop traversing further right subtree. Similarly, if the current node value is smaller than 'low', you can avoid traversing the left subtree further.
Time Complexity: O(N), where N is the number of nodes in the tree since in the worst case we must visit all nodes.
Space Complexity: O(H), where H is the height of the tree (accounting for the recursion stack).
1
2function TreeNode(val, left, right) {
3 this.val = (val===undefined ? 0 : val)
4 this.left = (left===undefined ? null : left)
5 this.right = (right===undefined ? null : right)
6}
7
8var rangeSumBST = function(root, low, high) {
9 if (!root) return 0;
10 if (root.val < low)
11 return rangeSumBST(root.right, low, high);
12 if (root.val > high)
13 return rangeSumBST(root.left, low, high);
14 return root.val + rangeSumBST(root.left, low, high) + rangeSumBST(root.right, low, high);
15};
16
This JavaScript code defines a function rangeSumBST
that uses recursion. It leverages the BST properties to sum the values of nodes within the range by considering each node only once, and skipping unnecessary branches.
This approach uses an iterative method with an explicit stack to facilitate an in-order traversal. Utilizing a stack allows avoiding the function call stack and can handle larger trees without risking stack overflow in languages with limitations on recursion depth.
As we push nodes onto the stack, we continue to the leftmost node, then process nodes and move to the right, ensuring nodes are visited in non-decreasing order. Only nodes within the range are added to the sum.
Time Complexity: O(N) where N is the number of nodes.
Space Complexity: O(H) where H is the height of the tree due to the stack usage.
This C implementation of iterative in-order traversal uses a stack to simulate recursion. We start from the root, push all left children to the stack, and pop them to process, checking if they fall within the range to add to the sum.