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

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

题目链接:530. 二叉搜索树的最小绝对差 - 力扣(LeetCode)

思路:由于是二叉搜索树,先用中序遍历将节点存入数组中,再遍历数组相邻元素即可。

class Solution {
public:
    void qianxu(TreeNode* root,vector<int> &v){
        if(root->left)qianxu(root->left,v);
        v.push_back(root->val);
        if(root->right)qianxu(root->right,v);
    }
    int getMinimumDifference(TreeNode* root) {
        vector<int> v;
        qianxu(root,v);
        int result=abs(v[1]-v[0]);
        for(int i=2;i<v.size();i++ ){
            if(result>abs(v[i]-v[i-1]))result=abs(v[i]-v[i-1]);
        }
        return result;
    }
};

501.二叉搜索树中的众数 

题目链接:501. 二叉搜索树中的众数 - 力扣(LeetCode)

class Solution {
public:
    void qianxu(TreeNode* root,map<int,int>& m){
        if(root->left)qianxu(root->left,m);
        m[root->val]++;
        if(root->right)qianxu(root->right,m);
    }
    vector<int> findMode(TreeNode* root) {
        map<int,int>m;
        qianxu(root,m);
        vector<int>result;
        int max=0;
        for(map<int,int>::iterator it=m.begin();it!=m.end();it++){
            if(it->second>=max)max=it->second;
        }
        for(map<int,int>::iterator it=m.begin();it!=m.end();it++){
            if(it->second==max)result.push_back(it->first);
        }
        return result;
    }
};

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

题目链接:236. 二叉树的最近公共祖先 - 力扣(LeetCode)

思路:本题难点在于如何对二叉树进行自底向上的查找,即回溯。方法就是后序遍历。

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 && right != NULL) return right;
        else if (left != NULL && right == NULL) return left;
        else  { //  (left == NULL && right == NULL)
            return NULL;
        }

    }
};

 

posted @   SandaiYoung  阅读(7)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端
点击右上角即可分享
微信分享提示