给你一棵所有节点为非负值的二叉搜索树,请你计算树中任意两节点的差的绝对值的最小值。
示例:
输入:
1
\
3
/
2输出:
1解释:
最小绝对差为 1,其中 2 和 1 的差的绝对值为 1(或者 2 和 3)。
解题思路1: 这道题和上一道求和的题十分相似,不同的是差的绝对值最小值只能出现在相邻的两个节点之间,因此可以与上次一样,手下中序遍历树得到一个有序的链表,然后遍历链表,找出差的绝对值最小值。
class Solution {
List<Integer> list = new ArrayList<>();
public int getMinimumDifference(TreeNode root) {
order(root);
int i=0,min=Integer.MAX_VALUE;
while(i<list.size()-1){
int tmp = list.get(i+1)-list.get(i);
if(tmp<min){
min=tmp;
}
i++;
}
return min;
}
private void order(TreeNode root){
if(root == null) return;
order(root.left);
list.add(root.val);
order(root.right);
}
}
解题思路2:上一种方法中的遍历链表其实可以放到中序遍历树中来完成,只需要每次记录遍历的前一个节点就可。
class Solution {
TreeNode preNode = null;
int min = Integer.MAX_VALUE;
public int getMinimumDifference(TreeNode root) {
order(root);
return min;
}
private void order(TreeNode root){
if(root == null) return;
order(root.left);
if(preNode != null){
min = Math.min(min,root.val-preNode.val);
}
preNode = root;
order(root.right);
}
}