当前位置:网站首页>LeetCode_98_验证二叉搜索树
LeetCode_98_验证二叉搜索树
2022-07-30 13:55:00 【Fitz1318】
题目链接
题目描述
给你一个二叉树的根节点 root
,判断其是否是一个有效的二叉搜索树。
有效 二叉搜索树定义如下:
- 节点的左子树只包含 小于 当前节点的数。
- 节点的右子树只包含 大于 当前节点的数。
- 所有左子树和右子树自身必须也是二叉搜索树。
示例 1:
输入:root = [2,1,3]
输出:true
示例 2:
输入:root = [5,1,4,null,null,3,6]
输出:false
解释:根节点的值是 5 ,但是右子节点的值是 4 。
提示:
- 树中节点数目范围在
[1, 10^4]
内 -2^(31) <= Node.val <= 2^(31) - 1
解题思路
二叉搜索树的中序遍历是一个数值递增的有序序列
AC代码
递归法
class Solution {
TreeNode pre = null;
public boolean isValidBST(TreeNode root) {
if(root == null){
return true;
}
boolean left = isValidBST(root.left);
if(pre != null && pre.val>= root.val){
return false;
}
pre = root;
boolean right = isValidBST(root.right);
return left && right;
}
}
迭代法
class Solution {
public boolean isValidBST(TreeNode root) {
if (root == null) {
return true;
}
Stack<TreeNode> stack = new Stack<>();
TreeNode pre = null;
while (root != null || !stack.isEmpty()) {
while (root != null) {
stack.push(root);
root = root.left;
}
TreeNode tmp = stack.pop();
if (pre != null && tmp.val <= pre.val) {
return false;
}
pre = tmp;
root = tmp.right;
}
return true;
}
}
边栏推荐
- 如何在 TiDB Cloud 上使用 Databricks 进行数据分析 | TiDB Cloud 使用指南
- Desktop Software Development Framework Awards
- [ARC092B] Two Sequences
- sql server安装失败怎么办(sql server安装不了怎么办)
- [论文翻译] Unpaired Image-To-Image Translation Using Cycle-Consistent Adversarial Networks
- 代码杂谈:从一道面试题看学会Rust的难度
- (HR Interview) Most Common Interview Questions and Skilled Answers
- Flask Framework - Flask-Mail Mail
- MQTT网关读取西门子PLC数据传输到阿里云平台案例教程
- Before quitting, make yourself a roll king
猜你喜欢
LeetCode二叉树系列——199二叉树的右视图
Data Middle Office Construction (5): Breaking Enterprise Data Silos and Extracting Data Value
43.【list链表的定义及初始化】
自动化测试之数据驱动DDT详细篇
Flask框架——Sijax
3年软件测试经验面试要求月薪22K,明显感觉他背了很多面试题...
电池包托盘有进水风险,存在安全隐患,紧急召回52928辆唐DM
LeetCode二叉树系列——107.二叉树的层序遍历II
Conversion between pytorch and keras (the code takes LeNet-5 as an example)
Flask框架——Flask-Mail邮件
随机推荐
记面试外包公司的一次经历,到底该不该去?
Flask框架——Flask-SQLite数据库
ccs软件的使用(靠谱挣钱的app软件)
重保特辑|拦截99%恶意流量,揭秘WAF攻防演练最佳实践
CF780G Andryusha and Nervous Barriers
百家号取消接口发文功能:插外链获权重被堵死
ddl and dml in sql (the difference between sql and access)
20220729 Securities, Finance
00 testers of seasoning after nearly a year, whether to change careers or to learn the software testing students summarized the following heart advice
The way of programmers' cultivation: do one's own responsibilities, be clear in reality - lead to the highest realm of pragmatism
Why did I switch from developer to testing, 3 years software testing engineer, tell you the secret of this
43.【list的简单属性】
Machine learning difference in the competition and industry application
43.【list链表的定义及初始化】
5. DOM
LeetCode二叉树系列——144.二叉树的最小深度
Eight years of testing experience, why was the leader criticized: the test documents you wrote are not as good as those of fresh graduates
ARC117E零和范围2
3年软件测试经验面试要求月薪22K,明显感觉他背了很多面试题...
[C# 循环跳转]-C# 中的 while/do-while/for/foreach 循环结构以及 break/continue 跳转语句