530. Minimum Absolute Difference in BST

Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes.

Example:

Input:

   1
    \
     3
    /    2

Output: 1

Explanation: The minimum absolute difference is 1, which is the
difference between 2 and 1 (or between 2 and 3). 

Note: There are at least two nodes in this BST.

思路1:

用一个list,存储全部的TreeNode。在list中,计算任意两个数之差的绝对值,求这个绝对值的最小值。 时间复杂度O(n2)。

思路2:

题目给的是BST树,可以利用BST树的性质:左子树中节点的最大值 < 根 < 右子树中节点的最小值
两个TreeNode之差的绝对值的最小值一定出现在 | 左 - 根 | 或 | 根 - 右 |之中。而非 | 右 - 左 |。
所以,只要从root,把树分成左子树和右子树,分别来计算就可以了。 这是第一个条件。

第二个条件, 根的值一定介于:左子树的最右节点右子树的最左节点 之间。
举个例子,236介于227和240之间:

这里写图片描述

根据这个原则,可以分别写两个函数求左子树的最右节点,和右子树的最左节点。然后分别递归左子树和右子树。
不过这种方法有一个缺点,就是每次都需要求左子树的最右节点,和右子树的最左节点。

Java 代码如下:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int getMinimumDifference(TreeNode root) {
        int min = Integer.MAX_VALUE;
        if(root == null) return min;
        TreeNode leftChildMostRight = getLeftChildMostRight(root.left);
        TreeNode rightChildMostLeft = getRightChildMostLeft(root.right);
        if(leftChildMostRight != null) {
            min = Math.min(min, Math.abs(leftChildMostRight.val - root.val));
        }
        if(rightChildMostLeft != null) {
            min = Math.min(min, Math.abs(rightChildMostLeft.val - root.val));
        }
        int min1 = Math.min(min, getMinimumDifference(root.left));
        int min2 = Math.min(min, getMinimumDifference(root.right));
        return Math.min(min, Math.min(min1, min2));
    }

    // 左子树的最右节点
    public TreeNode getLeftChildMostRight(TreeNode root) {
        if(root == null) {
            return root; 
        }
        while(root.right != null) {
            root = root.right;
        }    
        return root;
    }

    // 右子树的最左节点
    public TreeNode getRightChildMostLeft(TreeNode root) {
        if(root == null) {
            return root; 
        }
        while(root.left != null) {
            root = root.left;
        }    
        return root;
    }

}

这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值