LeetCode刷题实战530:二叉搜索树的最小绝对差
Given the root of a Binary Search Tree (BST), return the minimum absolute difference between the values of any two different nodes in the tree.
示例
解题
思路:利用二叉搜索树-中序遍历递归
class Solution {
// 二叉搜索树的最小绝对差
int min_diff = Integer.MAX_VALUE;
int pre = -1;
public int getMinimumDifference(TreeNode root) {
// 中序遍历
if(root==null){
return min_diff;
}
// 左根右
getMinimumDifference(root.left);
if(pre!=-1){
min_diff = Math.min(Math.abs(root.val-pre),min_diff);
pre = root.val;
}else{
pre = root.val;
}
getMinimumDifference(root.right);
return min_diff;
}
}
评论