938. Range Sum of BST
Input: root = [10,5,15,3,7,null,18], L = 7, R = 15
Output: 32Input: root = [10,5,15,3,7,13,18,1,null,6], L = 6, R = 10
Output: 23解题要点:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int sum = 0;
public int rangeSumBST(TreeNode root, int L, int R) {
if(root == null) return 0;
if(L <= root.val && root.val <= R){
sum += root.val;
}
if(L < root.val) rangeSumBST(root.left, L, R);
if(R > root.val) rangeSumBST(root.right, L, R);
return sum;
}
}Last updated