当前位置:网站首页>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;
}
};
边栏推荐
- 第 1 章 一大波数正在靠近——排序
- What are the basic steps to develop a quantitative trading strategy?
- 18-GuliMall 压力测试与性能监控
- 用户要清晰知道,量化交易并非简单的程序
- Day 12 of learning to program
- 2022-8-9 第六组 输入输出流
- Interfering with BGP routing---community attributes
- 【TS技术课堂】时间序列预测
- Basic operations of xlrd and xlsxwriter
- R语言拟合ARIMA模型并使用拟合模型进行预测推理:使用forecast函数计算ARIMA模型未来值(包含时间点、预测值、两个置信区间)
猜你喜欢

leetcode brush questions diary Calculate the number of elements on the right that is less than the current element

Transfer Learning & Kemin Initialization

Postgresql源码(68)virtualxid锁的原理和应用场景

Core Data浅谈系列之五 : 在UITableView中展示

Socket发送缓冲区接收缓冲区快问快答

少儿编程 电子学会图形化编程等级考试Scratch三级真题解析(判断题)2022年6月

shell数组

Jinshanyun earthquake, the epicenter is in bytes?

DXF笔记:文字对齐的研究

Leetcode.25 K个一组翻转链表(模拟/递归)
随机推荐
高数_复习_第4章:向量代数和空间解析几何
Vmware中安装win7虚拟机以及相关简单知识
How to insist to use procedural system?
反射机制篇
chart.js面积图曲线图统计插件
setter与getter访问器属性——数据驱动显示
Qt 消息机制和事件
D. Binary String To Subsequences
xlrd 与 xlsxwritter 的基本操作
shell学习
注意力引导网络用于视网膜图像分割
What kind of mentality do you need to have when using the stock quantitative trading interface
PyQt5: Getting Started Tutorial
【Burning】It's time to show your true strength!Understand the technical highlights of the 2022 Huawei Developer Competition in one article
十步以内,用小程序快速生成App!
使用股票量化交易接口需要具备怎么样的心态
three.js镂空圆球拖拽变形js特效
Basic operations of xlrd and xlsxwriter
Chapter 15 HMM模型
Janus官方DEMO介绍