给你一个二叉搜索树的根节点 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);
}
}
标签:right,TreeNode,val,int,最小,二叉,搜索,root,left
From: https://www.cnblogs.com/xiaochaofang/p/17594442.html