代码随想录算法训练营第二十一天| 530.二叉搜索树的最小绝对差、501.二叉搜索树中的众数、236. 二叉树的最近公共祖先

530.二叉搜索树的最小绝对差

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

和验证二叉搜索树其实是一个逻辑,利用一个pre来记录前一位的二叉树节点,再用一个min变量来记录当前节点和前一个节点的差值,只要差值比min记录的更小,就更新min

class Solution {
public:
    TreeNode* pre = nullptr;
    int min = INT_MAX;
    int getMinimumDifference(TreeNode* root) {
        if(root->left) getMinimumDifference(root->left);
        if(pre) min = min < root->val - pre->val ? min : root->val - pre->val;
        pre = root;
        if(root->right) getMinimumDifference(root->right);
        return min;
    }
};

501.二叉搜索树中的众数

https://leetcode.cn/problems/find-mode-in-binary-search-tree/

寻找众数和找最小绝对差是一个思路,需要用一个count变量来记录当前元素出现的次数,用一个maxcount来记录最大count,只要count比maxcount大了就更新maxcount并且更新result

class Solution {
public:
    int maxCount = 0;
    int count = 0;
    TreeNode* pre = nullptr;
    vector<int> result = {};
    void traversal(TreeNode* cur){
        if(!cur) return; 
        traversal(cur->left);
        if(!pre) count = 1;
        else if(pre->val == cur->val) count++;
        else count = 1;
        pre = cur;
        if(count == maxCount) result.push_back(cur->val);
        if(count > maxCount){
            result.clear();
            result.push_back(cur->val);
            maxCount = count;
        }
        traversal(cur->right);
    }
    vector<int> findMode(TreeNode* root) {
        traversal(root);
        return result;
    }
};

236. 二叉树的最近公共祖先

https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-tree/

本题采用后序遍历,左、右、中的顺序更容易发现公共祖先

如果遍历到最后还没有找到目标节点就返回空节点

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(!root || root == p || root == q) return root;
        TreeNode* left = lowestCommonAncestor(root->left, p, q);
        TreeNode* right = lowestCommonAncestor(root->right, p, q);
        if(left && right) return root;
        if(left && !right) return left;
        if(!left && right) return right;
        return nullptr;
    }
};

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值