Skip to content

Commit d4e336a

Browse files
committedApr 28, 2019
LeetCode打卡第二十七天——二叉搜索树最小距离
1 parent b6c95e1 commit d4e336a

File tree

1 file changed

+86
-0
lines changed

1 file changed

+86
-0
lines changed
 

‎MinimumDistanceBetweenBSTNodes.md

+86
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
---
2+
Time:2019/4/27
3+
Title: Minimum Distance Between BST Nodes
4+
Difficulty: Easy
5+
Author: 小鹿
6+
---
7+
8+
9+
10+
## 题目:Minimum Distance Between BST Nodes(二叉搜索树结点最小距离)
11+
12+
Given a Binary Search Tree (BST) with the root node `root`, return the minimum difference between the values of any two different nodes in the tree.
13+
14+
> 给定一个二叉搜索树的根结点 `root`, 返回树中任意两节点的差的最小值。
15+
16+
**Example :**
17+
18+
```
19+
Input: root = [4,2,6,1,3,null,null]
20+
Output: 1
21+
Explanation:
22+
Note that root is a TreeNode object, not an array.
23+
24+
The given tree [4,2,6,1,3,null,null] is represented by the following diagram:
25+
26+
4
27+
/ \
28+
2 6
29+
/ \
30+
1 3
31+
32+
while the minimum difference in this tree is 1, it occurs between node 1 and node 2, also between node 3 and node 2.
33+
```
34+
35+
**Note:**
36+
37+
1. The size of the BST will be between 2 and `100`.
38+
2. The BST is always valid, each node's value is an integer, and each node's value is different.
39+
40+
41+
42+
## Solve:
43+
44+
###### ▉ 问题分析
45+
46+
47+
48+
###### ▉ 算法思路
49+
50+
51+
52+
###### ▉ 代码实现
53+
54+
```javascript
55+
var minDiffInBST = function(root) {
56+
if(root == null) return null;
57+
let arr = [];
58+
let min = Number.MAX_VALUE
59+
60+
distance = (root)=>{
61+
if(root == null) return null;
62+
distance(root.left)
63+
arr.push(root.val);
64+
distance(root.right)
65+
}
66+
67+
distance(root);
68+
69+
for(let i = 1;i < arr.length;i++){
70+
min = Math.min(min,arr[i] - arr[i - 1])
71+
}
72+
return min;
73+
};
74+
```
75+
76+
77+
78+
79+
80+
81+
82+
83+
84+
85+
86+

0 commit comments

Comments
 (0)
Failed to load comments.