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.
寻找到比root节点小的节点中的最大值,和比root节点大的节点中的最小值。通过这三个值的比较得出最小的diff,递归下去。此方法并没有完全利用到BST的特性,因此,效率不高。
public int minDiffInBST(TreeNode root) {
if (root == null) return Integer.MAX_VALUE;
int res = 0;
int minL = Integer.MAX_VALUE;
int minR = Integer.MAX_VALUE;
if (root.left !=null){
minL = root.val - BST_max(root.left).val;
}
if (root.right != null) {
minR = BST_min(root.right).val - root.val;
}
res = Math.min(minL,minR);
return Math.min( res,Math.min(minDiffInBST(root.left),minDiffInBST(root.right)));
}
public TreeNode BST_min(TreeNode root){
if (root.left == null) return root;
return BST_min(root.left);
}
public TreeNode BST_max(TreeNode root){
if (root.right == null) return root;
return BST_max(root.right);
}
我们知道,对于一个BST来说,中序遍历得到的顺序就是节点的从小到大的顺序排列的,因此可以采用一个变量prev,记录上一个节点的,采用当前节点的值减去上一个节点的值(prev),就可以得到相邻排序的两个节点的差值,一次循环下去,就可以方便的得出最小值。
int minDiff = Integer.MAX_VALUE;
TreeNode prev;
public int minDiffInBST(TreeNode root) {
int res = Integer.MAX_VALUE;
inOrderBST(root);
return minDiff;
}
public void inOrderBST(TreeNode root){
if (root == null) return;
inOrderBST(root.left);
if (prev != null) minDiff = Math.min(minDiff,root.val - prev.val);
prev = root;
inOrderBST(root.right);
}
Pick One
Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes.
Example:
Input:
1
\
3
/
2
Output:
1
Explanation:
TreeNode prev2 ;
int res = Integer.MAX_VALUE;
public int getMinimumDifference(TreeNode root) {
if (root==null) return 0;
getMinimumDifference(root.left);
if (prev2!=null) res = Math.min(res,root.val - prev2.val);
prev2 = root;
getMinimumDifference(root.right);
return res;
}
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。