[LintCode] Minimum Absolute Difference in BST

发布时间:2019-07-17 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了[LintCode] Minimum Absolute Difference in BST脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

Problem

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).

Solution

public class Solution {
    /**
     * @param root: the root
     * @return: the minimum absolute difference between values of any two nodes
     */
    private final int diff = Integer.MAX_VALUE;
    public int getMinimumDifference(TreeNode root) {
        // take root for example, the min diff should be the diff of 
        // 1. `root` and `root.left's rightmost child`
        // 2. `root` and `root.right's leftmost child`
        if (root == null) return diff;
        
        int res = Integer.MAX_VALUE, leftmost = -1, rightmost = -1;
        if (root.left != null) {
            rightmost = getRightMost(root.left);
        }
        if (root.right != null) {
            leftmost = getLeftMost(root.right);   
        }
        if (leftmost != -1) {
            res = Math.min(res, Math.abs(root.val - leftmost));
        }
        if (rightmost != -1) {
            res = Math.min(res, Math.abs(root.val - rightmost));
        }
        res = Math.min(res, getMinimumDifference(root.left));
        res = Math.min(res, getMinimumDifference(root.right));
        return res;
    }
    public int getLeftMost(TreeNode node) {
        while (node.left != null) node = node.left;
        return node.val;
    }
    public int getRightMost(TreeNode node) {
        while (node.right != null) node = node.right;
        return node.val;
    }
}

脚本宝典总结

以上是脚本宝典为你收集整理的[LintCode] Minimum Absolute Difference in BST全部内容,希望文章能够帮你解决[LintCode] Minimum Absolute Difference in BST所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: