题目描述:
给定二叉搜索树的根结点 root,返回 L 和 R(含)之间的所有结点的值的和。
二叉搜索树保证具有唯一的值。
示例 1:
输入:root = [10,5,15,3,7,null,18], L = 7, R = 15
输出:32
示例 2:
输入:root = [10,5,15,3,7,13,18,1,null,6], L = 6, R = 10
输出:23
提示:
树中的结点数量最多为 10000 个。
最终的答案保证小于 2^31。
首先这道题的结点的值和的意思是排序进行中序遍历的顺序,那么就是中序遍历后的顺序
比如示例1的中序遍历后为:3,5,7,10,15,18,那么在7和15之间的和就是7 + 10 + 15 = 32,示例2也是如此
那么就很简单,用一个全局变量来得出返回值,中序遍历时,每次判断是否在L和R之间
代码:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int get = 0;
//22点27分
//22点27分
public int rangeSumBST(TreeNode root, int L, int R) {
//进行中序遍历
int result = 0;
re(root, L, R,result);
return result;
}
public void re(TreeNode root,int L,int R,int result){
if(root == null){
return;
}
re(root.left, L, R,result);
if(root.val >= L && root.val <= R){
result+=root.val;
}
if(root.val > R)
return;
re(root.right, L, R,result);
}
}