当前位置:网站首页>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;
}
};
边栏推荐
- 对象深复制,面试题
- Common commands and technical function modules of Metasploit
- 数字与中文大写数字互转(5千万亿亿亿亿以上的数字也支持转换)
- 【Burning】It's time to show your true strength!Understand the technical highlights of the 2022 Huawei Developer Competition in one article
- 【Apifox】为什么如此受青睐,此篇文章和大家分享
- 阿里云架构师金云龙:基于云XR平台的视觉计算应用部署
- Presto Event Listener开发
- CGLIB源码易懂解析
- R语言修改dataframe数据列的名称:使用dplyr包的rename函数修改列名、使用colnmaes函数修改列名、在数据筛选的时候重命名列名
- js array object deduplication
猜你喜欢
随机推荐
LeetCode_2632_字符串压缩
APS系统能消除造成生产和运输延迟的瓶颈
高数_复习_第4章:向量代数和空间解析几何
第 1 章 一大波数正在靠近——排序
R语言ggplot2可视化:使用ggpubr包的ggscatter函数可视化散点图、使用scale_x_continuous函数的breaks参数指定X轴的断点的个数(设置参数n)
xctf攻防世界 Web高手进阶区 shrine
JuiceFS 在多云存储架构中的应用 | 深势科技分享
leetcode 38. 外观数列
【LaTex】 Font “FandolSong-Regular“ does not contain requested(fontspec)Script “CJK“.如何抑制此种警告?
xctf攻防世界 Web高手进阶区 ics-05
shader学习笔记(五)
A1. Prefix Flip (Easy Version)
跨端技术方案选什么好?
Activiti7审批流
leetcode:320.列举单词的全部缩写
Basic operations of xlrd and xlsxwriter
pip 离线到内网安装包
mysql中的key是怎么用的,或者这个值有什么意义,如下图?
Qt 消息机制和事件
How do task flow executors work?