程式碼隨想錄演算法訓練營第18天| 530.二叉搜尋樹的最小絕對差, 501.二叉搜尋樹中的眾數 , 236. 二叉樹的最近公共祖先

W-Vicky11發表於2024-11-10

530.二叉搜尋樹的最小絕對差

文章連結:https://programmercarl.com/0530.二叉搜尋樹的最小絕對差.html
影片連結:https://www.bilibili.com/video/BV1DD4y11779/?vd_source=6cb513d59bf1f73f86d4225e9803d47b
題目連結:https://leetcode.cn/problems/minimum-absolute-difference-in-bst/

採用了上一題的方法:

class Solution {
public:
    TreeNode* pre=NULL;
    int getMinimumDifference(TreeNode* root) {
        //利用搜尋樹的左中右的順序
        if(root==NULL) return INT_MAX;
        //左
        int left=getMinimumDifference(root->left);
        //中
        if(pre!=NULL) left=min(left,root->val-pre->val);
        pre=root;
        //右
        int right=getMinimumDifference(root->right);
        return min(left,right);
    }
};

501.二叉搜尋樹中的眾數

文章連結:https://programmercarl.com/0501.二叉搜尋樹中的眾數.html
題目連結:https://leetcode.cn/problems/find-mode-in-binary-search-tree/description/
影片連結:https://www.bilibili.com/video/BV1fD4y117gp/?vd_source=6cb513d59bf1f73f86d4225e9803d47b

class Solution {
public:
    int count=1;
    int maxCount=1;
    queue<int> que;
    TreeNode* pre=NULL;
    void traversal(TreeNode* root){
        if(root==NULL) return;
        //左
        traversal(root->left);
        //中
        if(pre!=NULL&&root->val==pre->val) count++;
        else count=1;
        pre=root;
        if(count>maxCount){
                maxCount=count;
                while(!que.empty()) que.pop();
                que.push(pre->val);
            }
        else if(count==maxCount) que.push(pre->val);

        //右
        traversal(root->right);
    }
    vector<int> findMode(TreeNode* root) {
        traversal(root);
        vector<int> res;
        while(!que.empty()){
            res.push_back(que.front());
            que.pop();
        }
        return res;
    }
};

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

文章連結:https://programmercarl.com/0236.二叉樹的最近公共祖先.html
題目連結:https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-tree/description/

總結:這個題稍有難度,以後多做幾遍

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

相關文章