File tree Expand file tree Collapse file tree 3 files changed +34
-4
lines changed
solution/0938.Range Sum of BST Expand file tree Collapse file tree 3 files changed +34
-4
lines changed Original file line number Diff line number Diff line change @@ -101,6 +101,7 @@ Complete [solutions](https://github.com/doocs/leetcode/tree/master/solution) to
101
101
| 0184 | [ Department Highest Salary] ( https://github.com/doocs/leetcode/tree/master/solution/0184.Department%20Highest%20Salary ) | ` SQL ` |
102
102
| 0328 | [ Odd Even Linked List] ( https://github.com/doocs/leetcode/tree/master/solution/0328.Odd%20Even%20Linked%20List ) | ` Linked List ` |
103
103
| 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 ` |
104
105
105
106
106
107
### Hard
Original file line number Diff line number Diff line change 22
22
23
23
### 解法
24
24
25
- 需要返回二叉搜索树中所有大于等于L且小于等于R的节点值的和 ,则对每个节点进行遍历即可。
26
- - 若节点的值大于等于L且小于等于R ,则加入统计中,并继续搜索其子节点。
27
- - 因为是二叉搜索树,所以小于L的只需要搜索其右子节点,大于R的只需要搜索其左子节点 。
25
+ 需要返回二叉搜索树中所有大于等于 L 且小于等于 R 的节点值的和 ,则对每个节点进行遍历即可。
26
+ - 若节点的值大于等于 L 且小于等于 R ,则加入统计中,并继续搜索其子节点。
27
+ - 因为是二叉搜索树,所以小于 L 的只需要搜索其右子节点,大于 R 的只需要搜索其左子节点 。
28
28
- 等于的情况可以提出来单独处理,也可以不单独处理,单独处理只是会减少一些无用的迭代。
29
- 节点值等于L只需搜索右子节点,等于R只需搜索左子节点 。
29
+ 节点值等于 L 只需搜索右子节点,等于 R 只需搜索左子节点 。
30
30
31
31
``` python
32
32
class Solution :
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments