代码随想录算法训练营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;
    }
};
相关推荐
奋发向前wcx9 小时前
P2590 树的统计 题目解析
数据结构·算法·深度优先
额鹅恶饿呃11 小时前
C语言中的数据结构和变量
c语言·数据结构·算法
万法若空13 小时前
【数据结构-哈希表】哈希表原理
数据结构·算法·散列表
tachibana213 小时前
hot100 翻转二叉树(226)
java·数据结构·算法·leetcode
兰令水14 小时前
leecodecode【面试150】【2026.7.9打卡-java版本】
java·数据结构·leetcode·面试·职场和发展
A.零点16 小时前
期末复习,408考研数据结构:第一章绪论完整知识梳理与真题深度解读
c语言·数据结构·笔记·考研
阿文的代码库16 小时前
经典算法题剖析:按奇偶排序数组
数据结构·算法
玛卡巴卡ldf19 小时前
【LeetCode 手撕算法】(细节知识点总结)
java·数据结构·算法·leetcode·力扣
Yang_jie_0321 小时前
笔记:数据结构(链队列的相关判断条件)
数据结构·笔记
zmzb01031 天前
C++课后习题训练记录Day154
数据结构·c++·算法