给定一棵二叉搜索树,请你返回树中任意两节点之差的最小值。
数据范围:二叉树节点数满足
,二叉树的节点值满足
,保证每个节点的值都不同
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* public TreeNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return int整型
*/
public int minDifference(TreeNode root) {
// write code here
if (root == null) {
return -1;
}
return getMin(root);
}
private int getMin(TreeNode root) {
if (root.left != null && root.right != null) {
return Math.min(Math.min(root.val - root.left.val, root.right.val - root.val),
Math.min(getMin(root.right), getMin(root.left)));
} else if (root.left != null) {
return Math.min(root.val - root.left.val, getMin(root.left));
} else if (root.right != null) {
return Math.min(root.right.val - root.val, getMin(root.right));
} else {
return Integer.MAX_VALUE;
}
}
}