当前位置:网站首页>Leetcode 530. 二叉搜索树的最小绝对差
Leetcode 530. 二叉搜索树的最小绝对差
2022-08-09 22:08:00 【LuZhouShiLi】
Leetcode 530. 二叉搜索树的最小绝对差
题目
给你一个二叉搜索树的根节点 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 {
public:
vector<int> vec;
void traversal(TreeNode* root)
{
if(root == NULL)
{
return;
}
traversal(root->left);
vec.push_back(root->val);
traversal(root->right);
}
int getMinimumDifference(TreeNode* root) {
// 二叉搜索树 中序遍历是一个递增序列
vec.clear();
traversal(root);
if(vec.size() < 2)
{
return 0;
}
int result = INT_MAX;
for(int i = 1; i < vec.size(); i++)
{
if(result > vec[i] - vec[i - 1])
{
result = vec[i] - vec[i - 1];
}
}
return result;
}
};
边栏推荐
- xctf攻防世界 Web高手进阶区 ics-05
- What are the basic steps to develop a quantitative trading strategy?
- A. Common Prefixes
- 深度学习100例 —— 循环神经网络(RNN)实现股票预测
- 工作经验-组件封装(拖拽排序组件)
- 对象深复制,面试题
- 第 1 章 一大波数正在靠近——排序
- 【服务器数据恢复】SAN LUN映射出错导致文件系统数据丢失的数据恢复案例
- 【Leetcode】2104. Sum of Subarray Ranges
- Bi Sheng Compiler Optimization: Lazy Code Motion
猜你喜欢
随机推荐
leetcode 38. 外观数列
JuiceFS 在多云存储架构中的应用 | 深势科技分享
leetcode:332. 重新安排行程
LeetCode_2632_字符串压缩
FileZilla搭建FTP服务器图解教程
Basic operations of xlrd and xlsxwriter
Janus Official DEMO Introduction
Pytorch分布式训练/多卡训练DDP——模型初始化(torch.distribute 与 DDP的区别)
leetcode:323. 无向图中连通分量的数目
你的 Link Button 能让用户选择新页面打开吗?
R语言ggplot2可视化:使用ggplot2可视化散点图、使用labs参数自定义Y轴的轴标签文本(customize Y axis labels)
请讲一讲JS中的 for...in 与 for...of (上)
How do task flow executors work?
How to insist to use procedural system?
Flutter 绘制美不胜收的光影流动效果
Analyses the development status quo of stock trading
Liver all night to write a thirty thousand - word all the commands the SQL database, function, speaks clearly explain operators, content is rich, proposal collection + 3 even high praise!
反射机制篇
C. Omkar and Baseball
【GORM】模型关系-HasMany关系