给定二叉搜索树的根结点 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。
什么是二叉搜索树?
二叉查找树(Binary Search Tree),(又:二叉搜索树,二叉排序树)它或者是一棵空树,或者是具有下列性质的二叉树: 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值; 它的左、右子树也分别为二叉排序树。
二叉搜索树资料来自百度百科。
分析示例1
输入:root = [10,5,15,3,7,null,18], L = 7, R = 15
输出:32
LR间值为10,15,7,和为32.
继续分析可知root(根结点)为10。
那么该如何利用递归求和呢?
法一:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int rangeSumBST(TreeNode* root, int L, int R) {
if(root == NULL)//跟结点不存在则为空树,直接返回0
{
return 0;
}
if(root->val >=L && root->val <= R)
{
return root->val + rangeSumBST(root->left , L ,R) + rangeSumBST(root->right , L , R);
//递归,当前值和左右子树符合条件的值相加
}
return rangeSumBST(root->left, L, R) + rangeSumBST(root->right, L, R);//继续往下递归
}
};
法二:
基本相同,最后一步换种方式
class Solution {
public:
int rangeSumBST(TreeNode* root, int L, int R) {
if(root == NULL)return 0;
if(root->val <= R && root->val >= L)
return rangeSumBST(root->left, L ,R) +root->val + rangeSumBST(root->right, L ,R);
else if(root->val > R)
{
return rangeSumBST(root->left, L ,R);
}
else
{
return rangeSumBST(root->right, L ,R);
}
}
};