二叉搜索树的最小绝对差
给你一个二叉搜索树的根节点 root ,返回 树中任意两不同节点值之间的最小差值 。
差值是一个正数,其数值等于两值之差的绝对值。
示例 1:
输入:root = [4,2,6,1,3]
输出:1
示例 2:
输入:root = [1,0,48,null,null,12,49]
输出:1
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int getMinimumDifference(TreeNode root) {
//递归遍历所有元素的数值,排序之后找到临近最小差值
ArrayList<Integer> list = new ArrayList<Integer>();
getRootNumber(root,list);
list.sort(Comparator.naturalOrder());
int min = Integer.MAX_VALUE;
for(int i=0;i<list.size();i++){
if(i+1<list.size())min = Math.min(min,list.get(i+1) - list.get(i));
}
return min;
}
public void getRootNumber(TreeNode root,ArrayList list){
if(root==null)return;
list.add(root.val);
getRootNumber(root.left,list);
getRootNumber(root.right,list);
}
}
因为数据特殊性,中序遍历能够得到排列好的数据,直接递归中进行差值比较
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
int min = Integer.MAX_VALUE;
int left = Integer.MAX_VALUE;
public int getMinimumDifference(TreeNode root) {
//二叉树使用中序遍历能够得到排列好的数字,
if(root==null)return 0;
getMinimumDifference(root.left);
//我们在递归的时候用当前节点-上一个节点得到差值取最小
//这里使用取绝对值,这样不影响接下来计算
int a = Math.abs(left - root.val);
min = Math.min(a,min);
left = root.val;
getMinimumDifference(root.right);
return min;
}
}