|
1 | 1 | packagecom.fishercoder.solutions;
|
2 | 2 |
|
3 | 3 | importcom.fishercoder.common.classes.TreeNode;
|
| 4 | + |
4 | 5 | importjava.util.ArrayList;
|
5 | 6 | importjava.util.List;
|
6 | 7 |
|
7 |
| -/** |
8 |
| - * 938. Range Sum of BST |
9 |
| - * |
10 |
| - * Given the root node of a binary search tree, return the sum of values of all nodes with value between L and R (inclusive). |
11 |
| - * |
12 |
| - * The binary search tree is guaranteed to have unique values. |
13 |
| - * |
14 |
| - * Example 1: |
15 |
| - * Input: root = [10,5,15,3,7,null,18], L = 7, R = 15 |
16 |
| - * Output: 32 |
17 |
| - * |
18 |
| - * Example 2: |
19 |
| - * Input: root = [10,5,15,3,7,13,18,1,null,6], L = 6, R = 10 |
20 |
| - * Output: 23 |
21 |
| - * |
22 |
| - * Note: |
23 |
| - * The number of nodes in the tree is at most 10000. |
24 |
| - * The final answer is guaranteed to be less than 2^31. |
25 |
| - */ |
26 | 8 | publicclass_938 {
|
27 |
| -publicstaticclassSolution1 { |
28 |
| -publicintrangeSumBST(TreeNoderoot,intL,intR) { |
29 |
| -if (root ==null) { |
30 |
| -return0; |
31 |
| - } |
32 |
| -List<Integer>list =newArrayList<>(); |
33 |
| -dfs(root,L,R,list); |
34 |
| -returnlist.stream().mapToInt(num ->num).sum(); |
35 |
| - } |
| 9 | +publicstaticclassSolution1 { |
| 10 | +publicintrangeSumBST(TreeNoderoot,intL,intR) { |
| 11 | +if (root ==null) { |
| 12 | +return0; |
| 13 | +} |
| 14 | +List<Integer>list =newArrayList<>(); |
| 15 | +dfs(root,L,R,list); |
| 16 | +returnlist.stream().mapToInt(num ->num).sum(); |
| 17 | +} |
36 | 18 |
|
37 |
| -privatevoiddfs(TreeNoderoot,intl,intr,List<Integer>list) { |
38 |
| -if (root ==null) { |
39 |
| -return; |
40 |
| - } |
41 |
| -if (root.val <=r &&root.val >=l) { |
42 |
| -list.add(root.val); |
43 |
| - } |
44 |
| -dfs(root.left,l,r,list); |
45 |
| -dfs(root.right,l,r,list); |
| 19 | +privatevoiddfs(TreeNoderoot,intl,intr,List<Integer>list) { |
| 20 | +if (root ==null) { |
| 21 | +return; |
| 22 | + } |
| 23 | +if (root.val <=r &&root.val >=l) { |
| 24 | +list.add(root.val); |
| 25 | + } |
| 26 | +dfs(root.left,l,r,list); |
| 27 | +dfs(root.right,l,r,list); |
| 28 | + } |
46 | 29 | }
|
47 |
| - } |
48 | 30 | }
|