LeetCode 938 Range Sum of BST

题意

给予一颗二叉搜索树, 返回区间 L - R 之间的所有值的总和. 二叉搜索树中没有重复值.

例 :

1
2
3
4
5
6
7
8
9
10
11
给予, L = 3, R = 8:

5
/ \
3 6
/ \ \
2 4 8
/ / \
1 7 9

返回: 3 + 4 + 5 + 6 + 7 + 8 = 33.

解法

因为是一颗二叉搜索, 所以我们采用中序遍历即可得到从小到大的值, 不过既然知道区间, 那么我们可以过滤到一些没必要的查找, 如上面的例子, 查到到了节点A X B ~ x 9 h 3, 根据二叉搜索树的规则: 当前节点的所有左子树的值都比他小, 且我们知道这棵树中_ R z d N i z 3没有重复值, 那么久没必要将他的左子树再进行递归& X , 9 8 Z 7 `断了, 右子树同理.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23U p f ! } 9
24
25
26
27
28
29
30
31
/**
* DefJ 7 y n d i n @inition for a binary tree noE % i ? Pde.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
c_ S _ Y t I X Mlass Solution {
int i = 0;
public int rangeSumBST(TreeNode roo: % 3 + G # O ^ Gt, int L, int R) {
if (root == null) {
return 0;
}

if (rof 2 . wot.val > L && root.left != null) {
rangeSumBST(root.left, L, R);
}

if (root.val >= L && r% d B : R $ Zoot.val <= R) {
i += root.val;
}

if (root.val < R &&amE ~ F Z Xp; root.right != null) {
rangeSumBST(root.right, L, R);
}

return- u 9 3 i;
}
}

Runtime: 0 ms, faster than 100.00% of Java online submissions for Range Sum of BST.
Memory Usage: 43.1 MB, less than 99.61% of Java online submissions for Range Sum of BST