当前位置 : 首页 » 文章分类 :  算法  »  LeetCode.783.Minimum Distance Between BST Nodes BST的最小差值

LeetCode.783.Minimum Distance Between BST Nodes BST的最小差值

题目描述

783 Minimum Distance Between BST Nodes
https://leetcode-cn.com/problems/minimum-distance-between-bst-nodes/

Given a Binary Search Tree (BST) with the root node root, return the minimum difference between the values of any two different nodes in the tree.

Example :

Input: root = [4,2,6,1,3,null,null]
Output: 1
Explanation:
Note that root is a TreeNode object, not an array.

The given tree [4,2,6,1,3,null,null] is represented by the following diagram:

          4
        /   \
      2      6
     / \
    1   3

while the minimum difference in this tree is 1, it occurs between node 1 and node 2, also between node 3 and node 2.

Note:
The size of the BST will be between 2 and 100.
The BST is always valid, each node’s value is an integer, and each node’s value is different.


解题过程


LeetCode.530.Minimum Absolute Difference in BST 非负BST的最小绝对差
几乎相同,一个是最小绝对差,一个是最小差值。

二叉搜索树的中序遍历序列是一个升序序列,这是二叉搜索树的一个重要性质,巧妙利用这一性质可以解决一系列二叉搜索树问题。所以可以把BST看成和有序数组是等价的,一看到BST马上就要想到是有序数组。

时间复杂度 O(n),空间复杂度 O(n)

需要注意的是用例 2147483647,-2147483648] 结果超出了 int 表示范围,会溢出为-1,但LeetCode 判题 oj 没有这个用例。

private static class SolutionV2020 {
    private Long minDiff;
    private TreeNode pre;
    public int minDiffInBST(TreeNode root) {
        minDiff = Long.MAX_VALUE;
        pre = null;
        inOrder(root);
        return minDiff.intValue();
    }

    // 中序遍历,过程中更新minDiff
    private void inOrder(TreeNode root) {
        if (null == root) {
            return;
        }
        inOrder(root.left);
        if (null != pre) {
            minDiff = Math.min(minDiff, (long)root.val - (long)pre.val);
        }
        pre = root;
        inOrder(root.right);
    }
}

GitHub代码

algorithms/leetcode/leetcode/_783_MinimumDistanceBetweenBSTNodes.java
https://github.com/masikkk/algorithms/blob/master/leetcode/leetcode/_783_MinimumDistanceBetweenBSTNodes.java


上一篇 LeetCode.872.Leaf-Similar Trees 叶子序列相同的二叉树

下一篇 LeetCode.700.Search in a Binary Search Tree 在BST中搜索

阅读
评论
413
阅读预计2分钟
创建日期 2020-02-02
修改日期 2020-02-02
类别

页面信息

location:
protocol:
host:
hostname:
origin:
pathname:
href:
document:
referrer:
navigator:
platform:
userAgent:

评论