938. Range Sum of BST

/**
* 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) {
int out = 0;
out = rangeSumBSTHelper(root,L,R);
return out;
}
public static int rangeSumBSTHelper(TreeNode root, int L, int R){
if(root == null) return 0;
int total = 0;
if( root.val >= L && root.val <= R)
total+= root.val;
if (root.right != null)
total+= rangeSumBSTHelper(root.right,L,R);
if (root.left != null)
total+=rangeSumBSTHelper(root.left,L,R);
return total;
}
}

### Like this:

Like Loading...

*Related*