Leetcode: 938

1 minute read

938. Range Sum of BST

Given the root node of a binary search tree, return the sum of values of all nodes with value between L and R (inclusive).

The binary search tree is guaranteed to have unique values.

Example 1:

Input: root = [10,5,15,3,7,null,18], L = 7, R = 15
Output: 32
( 7, 10, 15) => the value between 7~ 15

Solutions:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
           int ans;
    public int rangeSumBST(TreeNode root, int L, int R) {
 
        
//         //iterative
//         int count = 0;
//         Stack<TreeNode> a = new Stack<>();
//         a.add(root);
//         while(a.size() > 0){
//             TreeNode temp = a.pop();
//             if(temp == null){
//                 continue;
//             }
//             if( temp.val > L) a.push( temp.left );
//             if( temp.val < R) a.push( temp.right );
//             if( L <= temp.val && temp.val <= R) count += temp.val; 
//         }
        
//         return count;
        
        //recursive
        if( root == null) return 0;
        if( root.val < L) return rangeSumBST( root.right, L, R);
        if( root.val > R) return rangeSumBST( root.left, L, R);
        
        //consider from this line, we need add the value together, so we need check the situation
        //up three lines give us method to do in different situations
        //so those are false situation
        return root.val + rangeSumBST( root.right, L, R) + rangeSumBST( root.left, L, R);

    }
}  

Offical solution:

class Solution {
    int ans;
    public int rangeSumBST(TreeNode root, int L, int R) {
        ans = 0;
        dfs(root, L, R);
        return ans;
    }

    public void dfs(TreeNode node, int L, int R) {
        if (node != null) {
            if (L <= node.val && node.val <= R)
                ans += node.val;
            if (L < node.val)
                dfs(node.left, L, R);
            if (node.val < R)
                dfs(node.right, L, R);
        }
    }
}

Updated: