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.

解法

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int i = 0;
public int rangeSumBST(TreeNode root, int L, int R) {
if (root == null) {
return 0;
}

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

if (root.val >= L && root.val <= R) {
i += root.val;
}

if (root.val < R && root.right != null) {
rangeSumBST(root.right, L, R);
}

return 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

  • 本文作者: 赵俊
  • 本文链接: http://www.zhaojun.im/leetcode-938/
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!