【leetcode】530. 二叉搜索树的最小绝对差(minimum-absolute-difference-in-bst)(模拟)[简单]

215 篇文章 0 订阅
66 篇文章 0 订阅

链接

https://leetcode-cn.com/problems/minimum-absolute-difference-in-bst/

耗时

解题:7 min
题解:4 min

题意

给你一棵所有节点为非负值的二叉搜索树,请你计算树中任意两节点的差的绝对值的最小值。

思路

二叉树一次 dfs 遍历出所有节点值,存入数组中,将得到的数组排序,那么最小的差值一定在数组的相邻两数中产生,遍历一次数组找相邻两数的差值最小值即可。

时间复杂度: O ( n l o g n ) O(nlogn) O(nlogn)

AC代码

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
private:
    vector<int> nums;

public:
    void dfs(TreeNode* root) {
        if(root == NULL) return ;
        nums.push_back(root->val);
        dfs(root->left);
        dfs(root->right);
    }
    
    int getMinimumDifference(TreeNode* root) {
        dfs(root);
        sort(nums.begin(), nums.end());
        int res = nums[1] - nums[0];
        int n = nums.size();
        for(int i = 2; i < n; ++i) {
            res = min(res, nums[i]-nums[i-1]);
        }
        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值