Skip to content

Commit 983ad50

Browse files
committed
feat(solution): add solution 0938 [Java]
Range Sum of BST
1 parent c2ebb39 commit 983ad50

File tree

3 files changed

+34
-4
lines changed

3 files changed

+34
-4
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,7 @@ Complete [solutions](https://github.com/doocs/leetcode/tree/master/solution) to
101101
| 0184 | [Department Highest Salary](https://github.com/doocs/leetcode/tree/master/solution/0184.Department%20Highest%20Salary) | `SQL` |
102102
| 0328 | [Odd Even Linked List](https://github.com/doocs/leetcode/tree/master/solution/0328.Odd%20Even%20Linked%20List) | `Linked List` |
103103
| 0343 | [Integer Break](https://github.com/doocs/leetcode/tree/master/solution/0343.Integer%20Break) | `Math`, `Dynamic Programming` |
104+
| 0938 | [Range Sum of BST](https://github.com/doocs/leetcode/tree/master/solution/0938.Range%20Sum%20of%20BST) | `Binary Search Tree` |
104105

105106

106107
### Hard

solution/0938.Range Sum of BST/README.md

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,11 +22,11 @@
2222

2323
### 解法
2424

25-
需要返回二叉搜索树中所有大于等于L且小于等于R的节点值的和,则对每个节点进行遍历即可。
26-
- 若节点的值大于等于L且小于等于R,则加入统计中,并继续搜索其子节点。
27-
- 因为是二叉搜索树,所以小于L的只需要搜索其右子节点,大于R的只需要搜索其左子节点
25+
需要返回二叉搜索树中所有大于等于 L 且小于等于 R 的节点值的和,则对每个节点进行遍历即可。
26+
- 若节点的值大于等于 L 且小于等于 R,则加入统计中,并继续搜索其子节点。
27+
- 因为是二叉搜索树,所以小于 L 的只需要搜索其右子节点,大于 R 的只需要搜索其左子节点
2828
- 等于的情况可以提出来单独处理,也可以不单独处理,单独处理只是会减少一些无用的迭代。
29-
节点值等于L只需搜索右子节点,等于R只需搜索左子节点
29+
节点值等于 L 只需搜索右子节点,等于 R 只需搜索左子节点
3030

3131
```python
3232
class Solution:
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* public class TreeNode {
4+
* int val;
5+
* TreeNode left;
6+
* TreeNode right;
7+
* TreeNode(int x) { val = x; }
8+
* }
9+
*/
10+
class Solution {
11+
private int res = 0;
12+
public int rangeSumBST(TreeNode root, int L, int R) {
13+
if (root == null) {
14+
return res;
15+
}
16+
17+
if (root.val < L) {
18+
rangeSumBST(root.right, L, R);
19+
} else if (root.val > R) {
20+
rangeSumBST(root.left, L, R);
21+
} else {
22+
res += root.val;
23+
rangeSumBST(root.left, L, R);
24+
rangeSumBST(root.right, L, R);
25+
}
26+
return res;
27+
28+
}
29+
}

0 commit comments

Comments
 (0)