当前位置:网站首页>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;
}
}
边栏推荐
- Remember an experience of interviewing an outsourcing company, should you go?
- 吃透Chisel语言.29.Chisel进阶之通信状态机(一)——通信状态机:以闪光灯为例
- OFDM 十六讲 3- OFDM Waveforms
- A new generation of open source free terminal tools, so cool
- Logic Vulnerability----Permission Vulnerability
- SQL 26 calculation under 25 years of age or older and the number of users
- pytorch学习记录(五):卷积神经网络的实现
- Synology system installation related file sharing
- 00 testers of seasoning after nearly a year, whether to change careers or to learn the software testing students summarized the following heart advice
- Six-faced ant financial clothing, resisting the bombardment of the interviewer, came to interview for review
猜你喜欢
随机推荐
(HR Interview) Most Common Interview Questions and Skilled Answers
Digital signal processing course lab report (what foundation is needed for digital signal processing)
无代码开发平台全部应用设置入门教程
自动化测试之数据驱动DDT详细篇
CF1677E Tokitsukaze and Beautiful Subsegments
新一代开源免费的终端工具,太酷了
eclipse连接SQL server数据库「建议收藏」
新时代背景下智慧城市的建设与5G技术有何关联
永州动力电池实验室建设合理布局方案
05 | login background: based on the password login mode (below)
[Advanced ROS] Lecture 11 Robot co-simulation based on Gazebo and Rviz (motion control and sensors)
【Advanced Mathematics】【7】Double Integral
UPC2022 Summer Individual Training Game 19 (B, P)
Allure进阶-动态生成报告内容
sql server安装失败怎么办(sql server安装不了怎么办)
近两年激光雷达运动物体分割论文阅读小结
简单理解精确率(Precision),召回率(Recall),准确率(Accuracy),TP,TN,FP,FN
HCIP(第十五天) —— 交换机(一)
关于String的一些思考
Why did I switch from developer to testing, 3 years software testing engineer, tell you the secret of this








