力扣 938. 二叉搜索树的范围和

题目说明

  • 给定二叉搜索树的根结点 root,返回值位于范围 [low, high] 之间的所有结点的值的和。
  • 提示:
    • 树中节点数目在范围 [1, 2 * 104]
    • 1 <= Node.val <= 105
    • 1 <= low <= high <= 105
    • 所有 Node.val 互不相同

示例

例1

image.png

1
2
输入:root = [10,5,15,3,7,null,18], low = 7, high = 15
输出:32

例2

image.png

1
2
输入:root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10
输出:23

笔者理解

此题是一道二叉搜索树问题,在力扣题库中被定义为简单题。

解法

当笔者阅读完此题后,发现此题直接对二叉搜索树进行中序遍历求解即可,让我们来看看具体如何实现的吧。

实现

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
// 将参数置为成员变量,方便调用
int low = 0;
int high = 0;
int result = 0;

// 表示前端是否结束
boolean isFirst = false;
// 表示后端是否开始
boolean isLast = false;

public int rangeSumBST(TreeNode root, int low, int high) {
this.low = low;
this.high = high;

inOrder(root);

return result;
}
public void inOrder(TreeNode root) {
if (root == null) {
return;
}

inOrder(root.left);

if (!isFirst && root.val >= low) {
isFirst = true;
}
if (!isLast && root.val > high) {
isLast = true;
}

// 进行异或操作,判断当前元素是不是区间内元素
result = isFirst ^ isLast? result + root.val: result;

inOrder(root.right);
}
}

时间和空间效率都还行,可见此解法还比较适合此题;

image.png

总结

本题是今天的每日一题,难度是为简单,感兴趣的朋友都可以去尝试一下,此题还有其他更多的解法,朋友们可以自己逐一尝试。