当前位置:网站首页>力扣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;
}
边栏推荐
猜你喜欢
Application practice | Shuhai supply chain construction of data center based on Apache Doris
How to remove the black dot in front of the title in word document
【C語言】符號的深度理解
Flutter TextField示例
Interpreting the development of various intelligent organizations in maker Education
Arcgis 10.2.2 | arcgis license server无法启动的解决办法
Compréhension approfondie du symbole [langue C]
迈动互联中标北京人寿保险
Redis03 - network configuration and heartbeat mechanism of redis
CloudCompare&Open3D DBSCAN聚类(非插件式)
随机推荐
minidom 模塊寫入和解析 XML
Rotary transformer string judgment
Go语言循环语句(第10课中3)
New intersectionobserver usage notes
Operation of adding material schedule in SolidWorks drawing
Word文档中标题前面的黑点如何去掉
面试题 01.08. 零矩阵
Use of class methods and class variables
How is the entered query SQL statement executed?
如何使用ConcurrentLinkedQueue做一个缓存队列
QT - double buffer plot
ArcGIS 10.2.2 | solution to the failure of ArcGIS license server to start
Go language loop statement (3 in Lesson 10)
置信区间的画法
【C語言】符號的深度理解
开户哪家券商比较好?网上开户安全吗
关系型数据库
TCP协议三次握手过程
GTEST from ignorance to proficient use (2) what is test fixture
开源之夏专访|Apache IoTDB社区 新晋Committer谢其骏