Leetcode_#530_二叉搜索树的最小绝对值差

原题:#530_二叉搜索树的最小绝对值差

  • 思路:
    • 二叉搜索树的中序遍历是有序的
    • 只需要比较相邻两个节点的值即可
private TreeNode preNode = null;
private int minDiff = Integer.MAX_VALUE;
public int f (TreeNode root) {
    helper(root);
    return minDiff;
}
public void helper(TreeNode root) {
    if (root == null) {
        return; 
    }
    helper(root.left);
    if (preNode != null) {
        minDiff = Math.min(minDiff, root.val - preNode.val);	//中序遍历是升序的,现在的节点值肯定比前一个节点值大,所以不用绝对值
    }
    preNode = root;
    helper(root.right);
}
原创文章 50 获赞 1 访问量 2912

猜你喜欢

转载自blog.csdn.net/u014642412/article/details/105952493
今日推荐