代码随想录算法训练营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;
    }
};
相关推荐
琢磨先生David6 天前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
qq_454245036 天前
基于组件与行为的树状节点系统
数据结构·c#
超级大福宝6 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
岛雨QA6 天前
常用十种算法「Java数据结构与算法学习笔记13」
数据结构·算法
weiabc6 天前
printf(“%lf“, ys) 和 cout << ys 输出的浮点数格式存在细微差异
数据结构·c++·算法
wefg16 天前
【算法】单调栈和单调队列
数据结构·算法
岛雨QA6 天前
图「Java数据结构与算法学习笔记12」
数据结构·算法
czxyvX6 天前
020-C++之unordered容器
数据结构·c++
岛雨QA6 天前
多路查找树「Java数据结构与算法学习笔记11」
数据结构·算法
AKA__Zas6 天前
初识基本排序
java·数据结构·学习方法·排序