Given therootnode of a binary search tree, return the sum of values of all nodes with value betweenLandR(inclusive).

The binary search tree is guaranteed to have unique values.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int rangeSumBST(TreeNode root, int L, int R) {
        if(root == null)
            return 0;

        if(L > root.val)
            return rangeSumBST(root.right, L, R);

        if(R < root.val)
            return rangeSumBST(root.left, L, R);

        int left = rangeSumBST(root.left, L, root.val);
        int right = rangeSumBST(root.right, root.val, R);
        return root.val + left + right;
    }
}

results matching ""

    No results matching ""