938. Range Sum of BST

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;
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s