当前位置:网站首页>LeetCode 783. 二叉搜索树节点最小距离 树/easy
LeetCode 783. 二叉搜索树节点最小距离 树/easy
2022-07-27 14:05:00 【押切徹】
1.Description
给你一个二叉搜索树的根节点 root ,返回 树中任意两不同节点值之间的最小差值 。
2.Example

输入:root = [4,2,6,1,3]
输出:1
3.Solution
使用中序遍历,计算当前节点和前一个节点的差值。
class Solution {
int pre;
int ans;
public int minDiffInBST(TreeNode root) {
ans = Integer.MAX_VALUE;
pre = -1;
dfs(root);
return ans;
}
public void dfs(TreeNode root) {
if (root == null) {
return;
}
dfs(root.left);
if (pre == -1) {
pre = root.val;
} else {
ans = Math.min(ans, root.val - pre);
pre = root.val;
}
dfs(root.right);
}
}
边栏推荐
- User question understanding and answer content organization for epidemic disease Science Popularization
- How to do well in enterprise system vulnerability assessment
- 什么是Tor?Tor浏览器更新有什么用?
- How to deploy open source Siyuan privately
- 网络设备硬核技术内幕 路由器篇 18 DPDK及其前传(三)
- 电子制造行业的数字化转型突破点在哪?精益制造是关键
- 腾讯二面:@Bean 与 @Component 用在同一个类上,会怎么样?
- 事务_基本演示和事务_默认自动提交&手动提交
- 网络设备硬核技术内幕 路由器篇 19 DPDK(四)
- STM32 - capacitive touch button experiment
猜你喜欢

被动收入:回归原始且安全的两种赚取方法

Finally, someone finished all the dynamic planning, linked list, binary tree and string required for the interview

Shell programming specifications and variables

If we were the developer responsible for repairing the collapse of station B that night
![Detailed explanation of Telnet remote login AAA mode [Huawei ENSP]](/img/48/dd0fa3c494c45f604b7a93c707b808.png)
Detailed explanation of Telnet remote login AAA mode [Huawei ENSP]

Stock trading 4

FPGA时序约束分享04_output delay 约束

动态规划——股票买卖5

大家最想要的,最全的C语言知识点总结,还不赶紧学习

Toward Fast, Flexible, and Robust Low-Light Image Enhancement(实现快速、灵活和稳健的弱光图像增强)CVPR2022
随机推荐
[Yunxiang book club issue 13] multimedia processing tool ffmpeg tool set
网络设备硬核技术内幕 路由器篇 14 从鹿由器到路由器 (中)
How to do well in enterprise system vulnerability assessment
Nokia's patent business was hit for the first time, and Chinese enterprises are not so easy to knead
aac 和 h264等的时间戳
什么是Tor?Tor浏览器更新有什么用?
If we were the developer responsible for repairing the collapse of station B that night
OBS 进阶之 DXGI 采集屏幕流程,并如何修改为自己的光标
The database uses PSQL and JDBC to connect remotely and disconnect automatically from time to time
网络设备硬核技术内幕 路由器篇 4 贾宝玉梦游太虚幻境(下)
STM32 - capacitive touch button experiment
获取Unity打开摄像头第一帧有画面的数据
Research on multi label patent classification based on pre training model
Getting started with DirectX
LeetCode 1143. 最长公共子序列 动态规划/medium
【WORK】关于技术架构
NEFU119 组合素数【算术基本定理】
Docker practical experience: deploy mysql8 master-slave replication on docker
FPGA时序约束分享04_output delay 约束
正则表达式:邮箱匹配