【LeetCode每日一题】783. 二叉搜索树节点最小距离

【LeetCode每日一题】783. 二叉搜索树节点最小距离

题目:

给你一个二叉搜索树的根节点 root ,返回 树中任意两不同节点值之间的最小差值 。

示例 1:

输入:root = [4,2,6,1,3]
输出:1

题解:

解法1:

存入数组中扫描。

class Solution {
public:
    int INF = 1e5+9;
    vector<int> res;
    int minDiffInBST(TreeNode* root) {
        inorder(root);
        int ans = INF;
        for (int i = 1; i < res.size(); i++) {
            ans = min(ans, res[i]-res[i-1]);
        }
        return ans;
    }

    void inorder(TreeNode* root) {
        if (!root) return;
        if (root->left) inorder(root->left);
        res.push_back(root->val);
        if (root->right) inorder(root->right);
    }
};

解法2:直接中序遍历拿到前一个结点比大小。

class Solution {
public:
    int INF = 1e5+9;
    int ans =  INF;
    TreeNode* pre = NULL;
    int minDiffInBST(TreeNode* root) {
        inorder(root);
        return ans;
    }

    void inorder(TreeNode* root) {
        if (!root) return;
        if (root->left) {
            inorder(root->left);
        }
        if (pre) {
            ans = min(ans, root->val-pre->val);
        }
        pre = root;
        if (root->right) {
            inorder(root->right);
        }
    }
};

本节完~

往日每日一题:

【LeetCode每日一题】83. 删除排序链表中的重复元素

【LeetCode每日一题】61. 旋转链表

【LeetCode每日一题】173. 二叉搜索树迭代器

【LeetCode每日一题】190. 颠倒二进制位

【LeetCode每日一题】74. 搜索二维矩阵

像树一样简单回溯递归【LeetCode每日一题】90. 子集 II

4月你好,愚人节果然是笨人,【LeetCode每日一题】1006. 笨阶乘

【LeetCode每日一题】面试题 17.21. 直方图的水量

不知不觉已经坚持8天了,你呢?【LeetCode每日一题】1143. 最长公共子序列

Day10【LeetCode每日一题】781. 森林中的兔子


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值