思路
看到二叉搜索树,就要想到他的中序遍历是递增数列。
然后这道题就很简单了。
代码
/**
* 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) {
if(root == null){
return 0;
}
List<Integer> list = new ArrayList<>();
fun(root,list);
int min = Integer.MAX_VALUE;
int length = list.size();
for(int i =0,j = i+1;i<length-1;i++,j++){
min = Math.min(min,Math.abs(list.get(i)-list.get(j)));
}
return min;
}
public void fun(TreeNode root,List list){
if(root == null){
return;
}
if(root.left != null){
fun(root.left,list);
}
list.add(root.val);
if(root.right != null){
fun(root.right,list);
}
}
}