class Solution {
private int res = Integer.MAX_VALUE;
TreeNode pre = null;
public int getMinimumDifference(TreeNode root) {
//二叉查找树中,中间节点的值一定是其左右节点值的中间数,因此最小差别一定是在中间节点与左右节点之间
getMin(root);
return res;
}
private void getMin(TreeNode root){
if(root==null)return;
getMin(root.left);
if(pre!=null){
res= Math.min(Math.abs(root.val - pre.val), res);
}
pre =root;
getMin(root.right);
}
}
每日算法:二叉树
最新推荐文章于 2024-02-27 06:00:41 发布