题目:给定二叉搜索树的根结点 root,返回 L 和 R(含)之间的所有结点的值的和。
二叉搜索树保证具有唯一的值。
题解思路:对中序遍历的值进行处理即可
package com.lcz.leetcode;
/**
* 二叉搜索树的范围和
* @author LvChaoZhang
*
*/
public class Leetcode938 {
class TreeNode{
int val;
TreeNode left;
TreeNode right;
TreeNode(int x){
val = x;
}
}
private int sum = 0;
public int rangeSumBST(TreeNode root,int L,int R) {
// 中序遍历来解决
return inorder(root,L,R);
}
private int inorder(TreeNode root,int L,int R) {
// 遍历截止条件
if(root==null) {
return 0;
}
// 左子树
inorder(root.left,L,R);
// 对结点的处理
if(root.val>=L&&root.val<=R) {
sum += root.val;
}
// 右子树
inorder(root.right,L,R);
return sum;
}
}