Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 3302fb3

Browse files
Merge pull request MisterBooo#92 from zzilcc/master
0530 solved
2 parents 0e9512c + b54bba9 commit 3302fb3

File tree

2 files changed

+95
-0
lines changed

2 files changed

+95
-0
lines changed
3.42 MB
Binary file not shown.
Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
# 530. 二叉搜索树的最小绝对差
2+
3+
> 本文首发于公众号「图解面试算法」,是 [图解 LeetCode ](<https://github.com/MisterBooo/LeetCodeAnimation>) 系列文章之一。
4+
>
5+
> 同步博客:https://www.algomooc.com
6+
7+
题目来源于 LeetCode 上 530. 二叉搜索树的最小绝对差. 是关于树的一道题。
8+
9+
## 题目
10+
11+
给你一棵所有节点为非负值的二叉搜索树,请你计算树中任意两节点的差的绝对值的最小值。
12+
13+
示例:
14+
15+
```
16+
输入:
17+
18+
1
19+
\
20+
3
21+
/
22+
2
23+
24+
输出:
25+
1
26+
27+
解释:
28+
最小绝对差为 1,其中 2 和 1 的差的绝对值为 1(或者 2 和 3)。
29+
```
30+
31+
提示:
32+
33+
树中至少有 2 个节点。
34+
本题与 783 https://leetcode-cn.com/problems/minimum-distance-between-bst-nodes/ 相同
35+
36+
37+
38+
## 题目解析
39+
40+
计算树中任意两节点的差的绝对值的最小值,那么肯定是要遍历树,然后相邻节点求差对比是不是最小的。
41+
二叉树的遍历有三种,前序遍历,中序遍历,后序遍历。
42+
43+
题目中给的是二叉搜索树,二叉搜索树有一个特色,就是中序遍历出来的结果,值是按照从小到大排列的。
44+
45+
所以我们只要中序遍历,保存上一个节点,然后遍历的时候取得当前节点和上一个节点的值的绝对值,如果比当前最小差还要小,那么更新最小差。
46+
47+
中序遍历是遍历左子树,然后根节点,最后是右子树,我们用递归去实现。
48+
49+
## 动画理解
50+
51+
52+
<video id="video" controls="" preload="none" >
53+
<source id="mp4" src="../Animation/0530.m4v" type="video/mp4">
54+
</video>
55+
56+
## 参考代码
57+
58+
59+
```javaScript
60+
/**
61+
* Definition for a binary tree node.
62+
* function TreeNode(val) {
63+
* this.val = val;
64+
* this.left = this.right = null;
65+
* }
66+
*/
67+
/**
68+
* @param {TreeNode} root
69+
* @return {number}
70+
*/
71+
var getMinimumDifference = function(root) {
72+
let min = Number.MAX_VALUE
73+
let preNode = null
74+
var travelTree = function (node) {
75+
if (node) {
76+
travelTree(node.left)
77+
if(preNode) {
78+
min = Math.min(min, Math.abs(preNode.val - node.val))
79+
}
80+
preNode = node
81+
travelTree(node.right)
82+
}
83+
}
84+
travelTree(root)
85+
return min
86+
};
87+
```
88+
89+
## 复杂度分析
90+
91+
时间复杂度:O(N),N为树中节点个数。
92+
93+
空间复杂度:O(log(N))。
94+
95+
![](../../Pictures/qrcode.jpg)

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /