二叉搜索树的范围和

LeetCode-938

  1. 首先需要仔细理解题目的意思:找出所有节点值在L和R之间的数的和。
  2. 这里采用递归来完成,主要需要注意二叉搜索树的性质。
/**
* 给定二叉搜索树的根结点 root,返回 L 和 R(含)之间的所有结点的值的和。
* 二叉搜索树保证具有唯一的值。
**/
#include<iostream>
#include<cstring>
#include<string>
#include<algorithm>
#include<cstdio>
#include<queue>
#include<vector>
using namespace std;
// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
/**
10
/ \
5 15
/ \ \
3 7 18
**/
class Solution {
private:
int sum=0;//
int l,r;
public:
void rangeSum(TreeNode* node){
//cout<<node->val<<endl;
if(node->val<=r&&node->val>=l){
sum+=node->val;
if(node->left)
rangeSum(node->left);
if(node->right)
rangeSum(node->right);
}else if(node->val<l){
if(node->right)
rangeSum(node->right);
}else if(node->val>r){
if(node->left)
rangeSum(node->left);
}
}
int rangeSumBST(TreeNode* root, int L, int R) {
this->l=L;
this->r=R;
if(root)
rangeSum(root);
return sum;
}
};
int main(){
TreeNode* t1=new TreeNode(10);
TreeNode* t2=new TreeNode(5);
TreeNode* t3=new TreeNode(15);
TreeNode* t4=new TreeNode(3);
TreeNode* t5=new TreeNode(7);
TreeNode* t6=new TreeNode(18);
t2->left=t4;t2->right=t5;
t3->left=t6;
t1->left=t2;t1->right=t3;
Solution solution;
cout<<solution.rangeSumBST(t1,7,15)<<endl;
system("pause");
return 0;
}

最新文章

  1. thinkjs中自定义sql语句
  2. UNTIY3D接入91SDK的办法
  3. posix and system V IPC
  4. [转]C#创建Windows服务与安装
  5. TSQL Challenge 1
  6. SQL Server 数据岸问题
  7. linux_根据关键词_路径下递归查找code
  8. UIAutomator源码分析之启动和运行
  9. kali2.0 + LAMP
  10. sha加密算法
  11. iOS技术框架构和更新版本的技术特性
  12. static(静态)关键字
  13. 初探APT攻击
  14. .net core 2.0 Unable to convert MySQL date/time to System.DateTime
  15. C# ComboBoxTree控件
  16. maven的动态打包功能
  17. mysql 外键理解
  18. 微信分享接口 略缩图 php
  19. redis集群环境的搭建和错误分析
  20. [转]An overview of Openvswitch implementation

热门文章

  1. HDU6532 Chessboard (最大费用流)
  2. Codeforces Round #630 (Div. 2)
  3. hdu3516 Tree Construction
  4. Codeforces Round #650 (Div. 3) E. Necklace Assembly (暴力)
  5. 牛客编程巅峰赛S1第5场 - 青铜&amp;白银 B.完全平方数的尾巴 (暴力)
  6. 错误: 未能完成程序集的安装(hr = 0x8007000b)。探测终止。
  7. QT串口助手(五):文件操作
  8. 【Azure Redis 缓存】使用Python代码获取Azure Redis的监控指标值 (含Powershell脚本方式)
  9. 快速获取 Wi-Fi 密码——GitHub 热点速览 v.21.06
  10. Zabbix 监控 SNMP &amp; JMX