代码随想录算法训练营DAY18第六章 二叉树part06

目录

[530. 二叉搜索树的最小绝对差](#530. 二叉搜索树的最小绝对差)

[501. 二叉搜索树中的众数](#501. 二叉搜索树中的众数)

[236. 二叉树的最近公共祖先](#236. 二叉树的最近公共祖先)


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

cpp 复制代码
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
    void dfs(TreeNode* root,int& pre,int& ans){
        if(!root)return ;
        dfs(root->left,pre,ans);
        if(pre==-1)pre=root->val;
        else {
            ans=min(ans,root->val-pre);
            pre=root->val;
        }
        dfs(root->right,pre,ans);
    }
public:
    int getMinimumDifference(TreeNode* root) {
        int ans=INT_MAX;
        int pre=-1;
        dfs(root,pre,ans);
        return ans;
    }
};

501. 二叉搜索树中的众数

cpp 复制代码
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
    int maxnum=0;
    unordered_map<int,int>map;
    void search(TreeNode* node) {
        if(!node)return;
        map[node->val]++;
        maxnum=max(maxnum,map[node->val]);
        search(node->left);
        search(node->right);
    }
public:
    vector<int> findMode(TreeNode* root) {
        search(root);
        vector<int> ans;
        for(auto& [key,value]:map){
            if(value==maxnum)ans.push_back(key);
        }
        return ans;
    }
};

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

cpp 复制代码
/**
 * 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 {
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;
        else if(left&&!right)return left;
        else if(!left&&right)return right;
        else return NULL;
    }
};
相关推荐
梵刹古音4 分钟前
【C语言】 指针与数据结构操作
c语言·数据结构·算法
爱敲代码的TOM1 小时前
数据结构总结
数据结构
皮皮哎哟3 小时前
数据结构:嵌入式常用排序与查找算法精讲
数据结构·算法·排序算法·二分查找·快速排序
堕2744 小时前
java数据结构当中的《排序》(一 )
java·数据结构·排序算法
2302_813806224 小时前
【嵌入式修炼:数据结构篇】——数据结构总结
数据结构
Wei&Yan5 小时前
数据结构——顺序表(静/动态代码实现)
数据结构·c++·算法·visual studio code
long3165 小时前
Aho-Corasick 模式搜索算法
java·数据结构·spring boot·后端·算法·排序算法
张张努力变强8 小时前
C++ STL string 类:常用接口 + auto + 范围 for全攻略,字符串操作效率拉满
开发语言·数据结构·c++·算法·stl
wWYy.8 小时前
数组快排 链表归并
数据结构·链表
李斯啦果8 小时前
【PTA】L1-019 谁先倒
数据结构·算法