当前位置:网站首页>Leetcode 98. 验证二叉搜索树
Leetcode 98. 验证二叉搜索树
2022-08-09 22:08:00 【LuZhouShiLi】
Leetcode 98. 验证二叉搜索树
题目
给你一个二叉树的根节点 root ,判断其是否是一个有效的二叉搜索树。
有效 二叉搜索树定义如下:
节点的左子树只包含 小于 当前节点的数。
节点的右子树只包含 大于 当前节点的数。
所有左子树和右子树自身必须也是二叉搜索树。
思路
- 二叉搜索树的中序遍历是一个有序序列,那么验证二叉搜索树只需要验证节点是否是有序的
- 先使用中序遍历,将每一个节点值存入数组中
- 之后判断数组是否是单调递增的
代码
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */
class Solution {
private:
vector<int> vec;// 存储二叉树节点
// 中序遍历 有序序列
void traversal(TreeNode* root)
{
if(root == NULL)
{
return ;
}
traversal(root->left);
vec.push_back(root->val);
traversal(root->right);
}
public:
bool isValidBST(TreeNode* root) {
vec.clear();
traversal(root);
for(int i = 1; i < vec.size();i++)
{
// 二叉树中不能有相同元素
if(vec[i] <= vec[i - 1])
{
return false;
}
}
return true;
}
};
边栏推荐
- chart.js面积图曲线图统计插件
- C. Binary String Reconstruction
- PyQt5:入门使用教程
- UNI-APP_监听页面滚动h5监听页面滚动
- xctf攻防世界 Web高手进阶区 ics-05
- UNI-APP_ monitor page scroll h5 monitor page scroll
- Day 12 of learning to program
- VR全景结合小程序,为线上电商更好的服务
- leetcode brush questions diary Calculate the number of elements on the right that is less than the current element
- 用户要清晰知道,量化交易并非简单的程序
猜你喜欢
随机推荐
华为鸿蒙3.0的野望:技术、应用、生态
What are the basic steps to develop a quantitative trading strategy?
用户要清晰知道,量化交易并非简单的程序
(转)FreeType字体位图属性
Arcgis工具箱无法使用,显示“XML包含错误“的解决方法
Qt message mechanism and events
leetcode:332. 重新安排行程
月薪5K的运维小白如何成为月薪5W的高级架构师?
OFDM 十六讲 7 - Inter-Symbol-Interference
mysql 、pg 查询日期处理
leetcode brush questions diary Calculate the number of elements on the right that is less than the current element
[Microservice~Nacos] Nacos service provider and service consumer
信息系统项目管理师---第十一章项目风险管理历年考题
R语言ggplot2可视化:使用ggplot2可视化散点图、使用labs参数自定义Y轴的轴标签文本(customize Y axis labels)
少儿编程 电子学会图形化编程等级考试Scratch三级真题解析(判断题)2022年6月
CV review: softmax code implementation
2022-8-9 第六组 输入输出流
阿里云架构师金云龙:基于云XR平台的视觉计算应用部署
Pytorch分布式训练/多卡训练DDP——模型初始化(torch.distribute 与 DDP的区别)
DXF笔记:文字对齐的研究