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 ( N log N ),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), where N is the number of nodes in the tree. We iterate over every node once.
-
Space Complexity: O(H), where H is the height of the tree. This is the space used by the implicit call stack when calling
dfs
.
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);
}
}