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
2#include <stdio.h>
3
4struct TreeNode {
5 int val;
6 struct TreeNode* left;
7 struct TreeNode* right;
8};
9
10int rangeSumBST(struct TreeNode* root, int low, int high) {
11 if (!root) return 0;
12 if (root->val < low)
13 return rangeSumBST(root->right, low, high);
14 if (root->val > high)
15 return rangeSumBST(root->left, low, high);
16 return root->val + rangeSumBST(root->left, low, high) + rangeSumBST(root->right, low, high);
17}
18
The function rangeSumBST
recursively explores each node. If the node's value is within the range [low, high], it adds this value to the total sum. If the node's value is less than low
, it skips to the node's right subtree. If the node's value is greater than high
, it skips to the node's left subtree.
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.