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.
Solution:分治
思路:
Time Complexity: O() Space Complexity: O()
Solution Code:
class Solution {
public int rangeSumBST(TreeNode root, int L, int R) {
if (root == null) {
return 0;
}
int sum = 0;
if (L < root.val) {
sum += rangeSumBST(root.left, L, R);
}
if (root.val < R) {
sum += rangeSumBST(root.right, L, R);
}
if (L <= root.val && root.val <= R) {
sum += root.val;
}
return sum;
}
}