您的位置:首页 > Web前端 > Node.js

Weekly Contest 71 leetcode 783. Minimum Distance Between BST Nodes

2018-02-11 14:11 369 查看
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.

Example :
Input: root = [4,2,6,1,3,null,null]
Output: 1
Explanation:
Note that root is a TreeNode object, not an array.

The given tree [4,2,6,1,3,null,null] is represented by the following diagram:

4
/   \
2      6
/ \
1   3

while the minimum difference in this tree is 1, it occurs between node 1 and node 2, also between node 3 and node 2.


Note:
The size of the BST will be between 2 and 
100
.
The BST is always valid, each node's value is an integer, and each node's value is different.
这道题蛮简单的。

public int minDiffInBST(TreeNode root) {
List<Integer> list=new ArrayList<Integer>();
dfs(root, list);
Collections.sort(list);
int min=Integer.MAX_VALUE;
for(int i=0;i<list.size()-1;i++){
int distance=list.get(i+1)-list.get(i);
min=Math.min(min, distance);
}
return min;
}

public void dfs(TreeNode node,List<Integer> list){
if(node!=null){
list.add(node.val);
dfs(node.left, list);
dfs(node.right, list);
}
}
这道题有solutions:https://leetcode.com/problems/minimum-distance-between-bst-nodes/solution/

我上面的方法复杂度是 O(NlogN),solutions中给出了一个的 O(N) 方法。

我这才发现,原来题目中是个BST(二叉搜索树),看来要好好读题啊。。。
在二叉搜索树中,中根遍历会按从小到大的顺序输出结点值。可以使用这个性质。

class Solution {
Integer prev, ans;
public int minDiffInBST(TreeNode root) {
prev = null;
ans = Integer.MAX_VALUE;
dfs(root);
return ans;
}

public void dfs(TreeNode node) {
if (node == null) return;
dfs(node.left);
if (prev != null)
ans = Math.min(ans, node.val - prev);
prev = node.val;
dfs(node.right);
}
}


Complexity Analysis

Time Complexity: O(N)O(N),
where NN is
the number of nodes in the tree. We iterate over every node once.

Space Complexity: O(H)O(H),
where HH is
the height of the tree. This is the space used by the implicit call stack when calling 
dfs
.

或者就直接按照中根遍历,把结点加到 list 中,最后再对 list 中的元素 一对一对 地比较。
class Solution {
int minDiff = Integer.MAX_VALUE;
public int minDiffInBST(TreeNode root) {
List<TreeNode> list = new LinkedList<TreeNode>();
inorder(root, list);
for(int i = 1; i < list.size(); i++)
minDiff = Math.min(minDiff, Math.abs((list.get(i).val)-(list.get(i-1).val)));
return minDiff;
}
private void inorder(TreeNode root, List<TreeNode> list){
if(root==null) return;
inorder(root.left, list);
list.add(root);
inorder(root.right, list);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: