当前位置:网站首页>力扣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;
}
边栏推荐
- Golang面试整理 三 简历如何书写
- What is business intelligence (BI), just look at this article is enough
- Analyzing the maker space contained in steam Education
- # 2156. 查找给定哈希值的子串-后序遍历
- 关系型数据库
- QT—双缓冲绘图
- MP3是如何诞生的?
- HDU - 2859 Phalanx(DP)
- Kubedm initialization error: [error cri]: container runtime is not running
- 电话加密,中间4为****代替
猜你喜欢

解析互联网时代的创客教育技术

How to implement Devops with automatic tools

保证接口数据安全的10种方案

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

Exclusive interview of open source summer | new committer Xie Qijun of Apache iotdb community
![[public class preview]: basis and practice of video quality evaluation](/img/fd/42b98a08b5a0fd89c119f1d1a8fe1b.png)
[public class preview]: basis and practice of video quality evaluation

bizchart+slider实现分组柱状图

【活动早知道】LiveVideoStack近期活动一览

Bizchart+slider to realize grouping histogram

Methods of improving machine vision system
随机推荐
Application practice | Shuhai supply chain construction of data center based on Apache Doris
minidom 模塊寫入和解析 XML
Hash table
Why do you have to be familiar with industry and enterprise business when doing Bi development?
QT—绘制其他问题
Minidom module writes and parses XML
Drop down selection of Ehlib database records
Kubedm initialization error: [error cri]: container runtime is not running
Use of class methods and class variables
Maidong Internet won the bid of Beijing life insurance
Open3D 曲面法向量计算
文件读取写入
How to implement Devops with automatic tools
做BI开发,为什么一定要熟悉行业和企业业务?
VS2019 C# release下断点调试
gtest从一无所知到熟练使用(4)如何用gtest写单元测试
CloudCompare&Open3D DBSCAN聚类(非插件式)
Case sharing | integrated construction of data operation and maintenance in the financial industry
OMS系统实战的三两事
[weekly translation go] how to code in go series articles are online!!