当前位置:网站首页>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;
}
}
边栏推荐
- LeetCode二叉树系列——107.二叉树的层序遍历II
- 二手手机销量突破3亿部,与降价的iPhone夹击国产手机
- redis6.0 源码学习(五)ziplist
- No-code development platform all application settings introductory tutorial
- Digital signal processing course lab report (what foundation is needed for digital signal processing)
- CF338E Optimize!
- AT4108 [ARC094D] Normalization
- 桌面软件开发框架大赏
- 【Pytorch】如何在关闭batch-norm的同时保持Dropout的开启
- UPC2022 Summer Individual Training Game 19 (B, P)
猜你喜欢

Flask Framework - Flask-Mail Mail
![[VMware virtual machine installation mysql5.7 tutorial]](/img/eb/4b47b859bb5695c38d48c8c01c9da0.png)
[VMware virtual machine installation mysql5.7 tutorial]

OFDM Sixteen Lectures 3- OFDM Waveforms

人社部公布“数据库运行管理员”成新职业,OceanBase参与制定职业标准

【Advanced Mathematics】【7】Double Integral

新时代背景下智慧城市的建设与5G技术有何关联

3 years of software testing experience, the interview requires a monthly salary of 22K, obviously he has memorized a lot of interview questions...

LeetCode二叉树系列——107.二叉树的层序遍历II

00后测试员摸爬滚打近一年,为是否要转行或去学软件测试的学弟们总结出了以下走心建议

3年软件测试经验面试要求月薪22K,明显感觉他背了很多面试题...
随机推荐
Conversion between pytorch and keras (the code takes LeNet-5 as an example)
无代码开发平台全部应用设置入门教程
20220729 Securities, Finance
OFDM 十六讲 3- OFDM Waveforms
数字信号处理课程实验报告(数字信号处理需要什么基础)
Interface automation framework, lm-easytest beta version released, use it quickly~
Flask Framework - Flask-Mail Mail
CF603E Pastoral Oddities
MIMO雷达波形设计
记面试外包公司的一次经历,到底该不该去?
pytorch学习记录(六):循环神经网络 RNN & LSTM
获取Google Advertising ID作为唯一识别码
[ARC092D] Two Faced Edges
近两年激光雷达运动物体分割论文阅读小结
Shell变量与赋值、变量运算、特殊变量、重定向与管渠
Cookie simulation login "recommended collection"
2022年,目前大环境下还适合转行软件测试吗?
Redis6.0 source code learning (5) ziplist
Synology system installation related file sharing
【VMware虚拟机安装mysql5.7教程】