Minimum Distance Between BST Nodes

本文介绍了一种在二叉搜索树中找到任意两个不同节点之间最小差值的方法。通过两种不同的中序遍历策略实现,第一种将遍历结果存储在列表中再寻找最小差值;第二种直接在遍历过程中更新最小差值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Minimum Distance Between BST Nodes

Description

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 1:

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.

Tags: Tree

解读题意

给定一个查找二叉树,找出该树中结点与结点间相减的最小值。

思路1

用中序遍历得到一个有序的数组,遍历数组找出相邻最小值即可。

class Solution {

    public int minDiffInBST(TreeNode root) {

        List<Integer> tempList = new ArrayList<>();

        int distance = Integer.MAX_VALUE;
        minDiffInBSTHelper(root,tempList);

        for (int i = 1; i < tempList.size(); i++) {
            distance = Math.min(distance,tempList.get(i)-tempList.get(i-1));
        }

        return distance;
    }

     private void minDiffInBSTHelper(TreeNode root, List<Integer> vals) {

        if (root == null)
            return;

        minDiffInBSTHelper(root.left, vals);
        vals.add(root.val);
        minDiffInBSTHelper(root.right, vals);

    }

}

time complexity:O(n)

思路2

与思路1一致,但是可以通过定义两个类变量而不用创建数组。

public class Solution1 {

    private int distance = Integer.MAX_VALUE;

    private Integer pre ;

    public int minDiffInBST(TreeNode root) {
        pre = null;

        if (root == null)
            return 0;

        minDiffInBSTHelper(root);

        return distance;
    }

    private void minDiffInBSTHelper(TreeNode root) {

        if (root == null)
            return;

        minDiffInBSTHelper(root.left);
        if(pre != null)
            distance = Math.min(distance, root.val - pre);

        pre = root.val;
        minDiffInBSTHelper(root.right);
    }

}

time complexity:O(n)

leetCode汇总:https://blog.youkuaiyun.com/qingtian_1993/article/details/80588941

项目源码,欢迎fork:https://github.com/mcrwayfun/java-leet-code

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值