当前位置:网站首页>力扣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;
}
边栏推荐
- Word文档中标题前面的黑点如何去掉
- Keep on fighting! The city chain technology digital summit was grandly held in Chongqing
- TCP协议三次握手过程
- 淘宝商品评价api接口(item_review-获得淘宝商品评论API接口),天猫商品评论API接口
- 类方法和类变量的使用
- Le module minidom écrit et analyse XML
- Application practice | Shuhai supply chain construction of data center based on Apache Doris
- At the right time, the Guangzhou station of the city chain science and Technology Strategy Summit was successfully held
- 从RepVgg到MobileOne,含mobileone的代码
- What is the stock account opening process? Is it safe to use flush mobile stock trading software?
猜你喜欢

开源之夏专访|Apache IoTDB社区 新晋Committer谢其骏

超详细教程,一文入门Istio架构原理及实战应用

Case sharing | integrated construction of data operation and maintenance in the financial industry

How was MP3 born?

Sorting and sharing of selected papers, systems and applications related to the most comprehensive mixed expert (MOE) model in history

Redis 排查大 key 的3种方法,优化必备

【公开课预告】:视频质量评价基础与实践

奋斗正当时,城链科技战略峰会广州站圆满召开

解读创客教育中的各类智能化组织发展

QT - double buffer plot
随机推荐
[C language] deep understanding of symbols
Bookmark
Open3D 曲面法向量计算
Compréhension approfondie du symbole [langue C]
面试官:说说XSS攻击是什么?
Interpreting the development of various intelligent organizations in maker Education
How was MP3 born?
[public class preview]: basis and practice of video quality evaluation
解析互联网时代的创客教育技术
AcWing 2022 每日一题
Jerry's ad series MIDI function description [chapter]
Shutter textfield example
面试题 01.01. 判定字符是否唯一
巅峰不止,继续奋斗!城链科技数字峰会于重庆隆重举行
应用实践 | 蜀海供应链基于 Apache Doris 的数据中台建设
Cloudcompare & open3d DBSCAN clustering (non plug-in)
MP3是如何诞生的?
Redis has three methods for checking big keys, which are necessary for optimization
Arcgis 10.2.2 | arcgis license server无法启动的解决办法
1807. 替换字符串中的括号内容