← Home

938. Range Sum of BST

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
stackC++Markdown
938

This problem looks busy at first, but the accepted solution is built around one steady invariant. For 938. Range Sum of BST, the solution in this repository is mainly a stack solution.

Guide

What?

Before optimizing anything, pin down what information is still useful after each move. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: stack, sliding window.

Guide

When?

Use this approach when the hard part is not syntax, but deciding what must stay true after every update. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are rangeSumBST.

Guide

Why?

The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.

  • The stack stores unfinished context, which is usually the cleanest way to handle nested or monotonic structure.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Start from the smallest reliable state.
  2. Expand one legal move at a time.
  3. Cache, count, or merge information as soon as it becomes settled.
  4. Let the final stored value answer the original question.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(N), where N is the number of nodes in the tree.
  • Space: O(H), where H is the height of the tree.

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01/**
02Given the root node of a binary search tree, return the sum of values of all nodes with value between L and R (inclusive).
03
04The binary search tree is guaranteed to have unique values.
05
06 
07
08Example 1:
09
10Input: root = [10,5,15,3,7,null,18], L = 7, R = 15
11Output: 32
12Example 2:
13
14Input: root = [10,5,15,3,7,13,18,1,null,6], L = 6, R = 10
15Output: 23
16 
17
18Note:
19
20The number of nodes in the tree is at most 10000.
21The final answer is guaranteed to be less than 2^31.
22**/
23
24/**
25 * Definition for a binary tree node.
26 * struct TreeNode {
27 *     int val;
28 *     TreeNode *left;
29 *     TreeNode *right;
30 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
31 * };
32 */
33
34/**
35Approach 1: Depth First Search
36Intuition and Algorithm
37
38We traverse the tree using a depth first search. If node.val falls outside the range [L, R], (for example node.val < L), then we know that only the right branch could have nodes with value inside [L, R].
39
40We showcase two implementations - one using a recursive algorithm, and one using an iterative one.
41
42Complexity Analysis
43
44Time Complexity: O(N), where N is the number of nodes in the tree.
45
46Space Complexity: O(H), where H is the height of the tree. 
47**/
48
49/**
50Your runtime beats 51.95 % of cpp submissions.
51**/
52
53class Solution {
54public:
55//    //recursive method, slower
56//     int sum = 0;
57//     int rangeSumBST(TreeNode* root, int L, int R) {
58//         if(root->left!=NULL){
59//             rangeSumBST(root->left, L, R);
60//         }
61//         if(root->val>=L && root->val<=R){
62//             sum+=root->val;
63//         }
64//         if(root->right!=NULL){
65//             rangeSumBST(root->right, L, R);
66//         }
67//         return sum;
68//     }
69 
70    //iterative method, faster
71    int rangeSumBST(TreeNode* root, int L, int R) {
72        int sum = 0;
73        std::stack<TreeNode*> stack = std::stack<TreeNode*>();
74        stack.push(root);
75        
76        while(!stack.empty()){
77            TreeNode* node = stack.top();
78            stack.pop(); //it returns NULL!
79            
80            if(node->val >= L && node->val <= R){
81                sum+=node->val;
82            }
83            //trimming
84            // if(node->left!=NULL && node->val >= L){
85            if(node->left && node->val >= L){
86                stack.push(node->left);
87            }
88            
89            // if(node->right!=NULL && node->val <= R){
90            if(node->right && node->val <= R){
91                stack.push(node->right);
92            }
93        }
94        return sum;
95    }
96};

Cost

Complexity

Time
O(N), where N is the number of nodes in the tree.
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(H), where H is the height of the tree.
Auxiliary state plus the answer structure where the problem requires one.