|
1 | 1 | package com.fishercoder.solutions;
|
2 | 2 |
|
3 | 3 | import com.fishercoder.common.classes.TreeNode;
|
| 4 | + |
4 | 5 | import java.util.ArrayList;
|
5 | 6 | import java.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 | public class _938 {
|
27 |
| - public static class Solution1 { |
28 |
| - public int rangeSumBST(TreeNode root, int L, int R) { |
29 |
| - if (root == null) { |
30 |
| - return 0; |
31 |
| - } |
32 |
| - List<Integer> list = new ArrayList<>(); |
33 |
| - dfs(root, L, R, list); |
34 |
| - return list.stream().mapToInt(num -> num).sum(); |
35 |
| - } |
| 9 | + public static class Solution1 { |
| 10 | + public int rangeSumBST(TreeNode root, int L, int R) { |
| 11 | + if (root == null) { |
| 12 | + return 0; |
| 13 | + } |
| 14 | + List<Integer> list = new ArrayList<>(); |
| 15 | + dfs(root, L, R, list); |
| 16 | + return list.stream().mapToInt(num -> num).sum(); |
| 17 | + } |
36 | 18 |
|
37 |
| - private void dfs(TreeNode root, int l, int r, 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 | + private void dfs(TreeNode root, int l, int r, 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 | }
|
0 commit comments