|
| 1 | +/** |
| 2 | + * Given the root node of a binary search tree, return the sum of values of all nodes with value between L and R (inclusive). |
| 3 | + * |
| 4 | + * The binary search tree is guaranteed to have unique values. |
| 5 | + * |
| 6 | + * |
| 7 | + * |
| 8 | + * Example 1: |
| 9 | + * |
| 10 | + * Input: root = [10,5,15,3,7,null,18], L = 7, R = 15 |
| 11 | + * Output: 32 |
| 12 | + * Example 2: |
| 13 | + * |
| 14 | + * Input: root = [10,5,15,3,7,13,18,1,null,6], L = 6, R = 10 |
| 15 | + * Output: 23 |
| 16 | + * |
| 17 | + * |
| 18 | + * Note: |
| 19 | + * |
| 20 | + * The number of nodes in the tree is at most 10000. |
| 21 | + * The final answer is guaranteed to be less than 2^31. |
| 22 | + */ |
| 23 | +public class RangeSumOfBST { |
| 24 | + public static void main(String[] args){ |
| 25 | + int L = 7, R = 15; |
| 26 | + RangeSumOfBST helper = new RangeSumOfBST(); |
| 27 | + System.out.println( |
| 28 | + "Range Sum of [" + L + "," + R + "] is : " + helper.rangeSumBST(helper.getTreeRootNode(), L, R)); |
| 29 | + } |
| 30 | + public int rangeSumBST(TreeNode root, int L, int R) { |
| 31 | + return getRangeSum(0, root, L, R); |
| 32 | + } |
| 33 | + |
| 34 | + private int getRangeSum(int currentSum, TreeNode root, int L, int R){ |
| 35 | + if(root == null) return 0; |
| 36 | + int sum = getRangeSum(currentSum, root.left, L, R); |
| 37 | + if(root.val >= L && root.val <=R){ |
| 38 | + sum += root.val; |
| 39 | + } |
| 40 | + return sum + getRangeSum(sum, root.right, L, R); |
| 41 | + } |
| 42 | + |
| 43 | + public class TreeNode { |
| 44 | + int val; |
| 45 | + TreeNode left; |
| 46 | + TreeNode right; |
| 47 | + TreeNode(int x) { val = x; } |
| 48 | + } |
| 49 | + |
| 50 | + public TreeNode getTreeRootNode(){ |
| 51 | + TreeNode root = new TreeNode(10); |
| 52 | + root.left = new TreeNode(5); |
| 53 | + root.left.left = new TreeNode(3); |
| 54 | + root.left.right = new TreeNode(7); |
| 55 | + root.right = new TreeNode(15); |
| 56 | + root.right.right = new TreeNode(18); |
| 57 | + return root; |
| 58 | + } |
| 59 | +} |
0 commit comments