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
2class TreeNode {
3public:
4 int val;
5 TreeNode* left;
6 TreeNode* right;
7 TreeNode(int v) : val(v), left(nullptr), right(nullptr) {}
8};
9
10class Solution {
11public:
12 int rangeSumBST(TreeNode* root, int low, int high) {
13 if (!root) return 0;
14 if (root->val < low)
15 return rangeSumBST(root->right, low, high);
16 if (root->val > high)
17 return rangeSumBST(root->left, low, high);
18 return root->val + rangeSumBST(root->left, low, high) + rangeSumBST(root->right, low, high);
19 }
20};
21
This C++ solution is structured similarly to the C solution. We define a Solution
class with a member function rangeSumBST
that performs a depth-first traversal of the tree, adding node values within the specified range.
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 Python implementation makes use of a manual stack to iterate in an in-order fashion without recursion, accumulating node sums that fall within the specified range.