当前位置:网站首页>力扣98:验证二叉搜索树
力扣98:验证二叉搜索树
2022-07-04 21:29:00 【瀛台夜雪】
力扣98:验证二叉搜索树
题目描述
给你一个二叉树的根节点 root ,判断其是否是一个有效的二叉搜索树。
有效 二叉搜索树定义如下:
节点的左子树只包含 小于 当前节点的数。
节点的右子树只包含 大于 当前节点的数。
所有左子树和右子树自身必须也是二叉搜索树。
输入输出样例

输入:root = [2,1,3]
输出:true

输入:root = [5,1,4,null,null,3,6]
输出:false
解释:根节点的值是 5 ,但是右子节点的值是 4 。
解法1:使用递归的思想实现
bool isValid(TreeNode *root,long long lower,long long upper)
{
if(root==nullptr)
{
return true;
}
if(root->val<=lower||root->val>=upper)
{
return false;
}
return isValid(root->left,lower,root->val)&&isValid(root->right,root->val,upper);
}
//使用递归的思想进行实现
bool isValidBST(TreeNode* root)
{
return isValid(root,LONG_MIN,LONG_MAX);
}
解法2:使用中序遍历
中序遍历二叉搜索树得到的也是一个升序的数组
//根据二叉搜索树中序遍历时升序的性质进行实现
bool isValidBST2(TreeNode* root)
{
if(!root)
{
return true;
}
stack<TreeNode *>stk;
vector<int>res;
while(!stk.empty()||root!=nullptr)
{
while(root!=nullptr)
{
stk.push(root);
root=root->left;
}
TreeNode *temp;
temp=stk.top();
// cout<<temp->val<<" ";
res.push_back(temp->val);
stk.pop();
root=temp->right;
}
int length=res.size();
for(int i=1;i<length;i++)
{
if(res[i]<=res[i-1])
{
return false;
}
}
return true;
}
边栏推荐
- Compréhension approfondie du symbole [langue C]
- Redis has three methods for checking big keys, which are necessary for optimization
- Arcgis 10.2.2 | arcgis license server无法启动的解决办法
- new IntersectionObserver 使用笔记
- Open3d surface normal vector calculation
- 做BI开发,为什么一定要熟悉行业和企业业务?
- [ 每周译Go ] 《How to Code in Go》系列文章上线了!!
- HDU - 2859 Phalanx(DP)
- New intersectionobserver usage notes
- [weekly translation go] how to code in go series articles are online!!
猜你喜欢

输入的查询SQL语句,是如何执行的?

Shutter textfield example

TCP shakes hands three times and waves four times. Do you really understand?

SolidWorks工程图添加材料明细表的操作

Master the use of auto analyze in data warehouse

创客思维在高等教育中的启迪作用

迈动互联中标北京人寿保险

QT—双缓冲绘图

Bizchart+slider to realize grouping histogram

ArcGIS 10.2.2 | solution to the failure of ArcGIS license server to start
随机推荐
Minidom module writes and parses XML
超详细教程,一文入门Istio架构原理及实战应用
Jerry's ad series MIDI function description [chapter]
从RepVgg到MobileOne,含mobileone的代码
Word文档中标题前面的黑点如何去掉
LambdaQueryWrapper用法
At the right time, the Guangzhou station of the city chain science and Technology Strategy Summit was successfully held
What is the stock account opening process? Is it safe to use flush mobile stock trading software?
Three or two things about the actual combat of OMS system
QT - plot other problems
Delphi SOAP WebService 服务器端多个 SoapDataModule 实现相同的接口方法,接口继承
SolidWorks工程图添加材料明细表的操作
How is the entered query SQL statement executed?
挖财学院股票开户安全吗?开户只能在挖财开户嘛?
Interviewer: what is XSS attack?
Jerry's ad series MIDI function description [chapter]
Analysis of maker education technology in the Internet Era
QT - double buffer plot
Maidong Internet won the bid of Beijing life insurance
Solve the problem of data disorder caused by slow asynchronous interface