当前位置:网站首页>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;
}
};
边栏推荐
- 浅析量股票化交易的发展现状
- R语言拟合ARIMA模型并使用拟合模型进行预测推理:使用forecast函数计算ARIMA模型未来值(包含时间点、预测值、两个置信区间)
- What kind of mentality do you need to have when using the stock quantitative trading interface
- 请讲一讲JS中的 for...in 与 for...of (上)
- &&、||、&、|
- leetcode:321. 拼接最大数
- Flask's routing (app.route) detailed
- 跨端技术方案选什么好?
- 【TS技术课堂】时间序列预测
- 重装系统后新建文本文档打不开怎么办
猜你喜欢

Js fifteen interview questions (with answers)

【技术分享】SLA(服务等级协议)原理与配置

Swift 需求 如何防止把view重复添加到win里面

JS中表单操作、addEventListener事件监听器

CV review: softmax code implementation

【LaTex】 Font “FandolSong-Regular“ does not contain requested(fontspec)Script “CJK“.如何抑制此种警告?

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

17-GuliMall 搭建虚拟域名访问环境

MySQL——JDBC

Qt 消息机制和事件
随机推荐
MySQL——JDBC
请讲一讲JS中的 for...in 与 for...of (上)
[WeChat applet development (8)] Summary of audio background music playback problems
setter与getter访问器属性——数据驱动显示
leetcode brush questions diary Calculate the number of elements on the right that is less than the current element
charts.js插件实现的散点图样式
电脑系统重装后怎么用打印机扫描出文件?
十步以内,用小程序快速生成App!
对象深复制,面试题
第十七期八股文巴拉巴拉说(数据库篇)
pip 离线到内网安装包
xlrd 与 xlsxwritter 的基本操作
跨端技术方案选什么好?
What kind of mentality do you need to have when using the stock quantitative trading interface
OSS文件上传
华为鸿蒙3.0的野望:技术、应用、生态
Presto Event Listener开发
What are the basic steps to develop a quantitative trading strategy?
C. Binary String Reconstruction
typedef和#define的花里胡哨的用法