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

目录

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

[701. 二叉搜索树中的插入操作](#701. 二叉搜索树中的插入操作)

[450. 删除二叉搜索树中的节点](#450. 删除二叉搜索树中的节点)


235. 二叉搜索树的最近公共祖先

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 (p->val < root->val && q->val < root->val)
            return lowestCommonAncestor(root->left, p, q);
        if (p->val > root->val && q->val > root->val)
            return lowestCommonAncestor(root->right, p, q);
        return root;
    }
};

701. 二叉搜索树中的插入操作

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 {
public:
    TreeNode* insertIntoBST(TreeNode* root, int val) {
        if(!root)return new TreeNode(val);
        if(val<root->val)root->left=insertIntoBST(root->left,val);
        else root->right=insertIntoBST(root->right,val);
        return root;
    }
};

450. 删除二叉搜索树中的节点

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 {
public:
    TreeNode* deleteNode(TreeNode* root, int key) {
        if(!root)return nullptr;
        if(key>root->val)root->right=deleteNode(root->right,key);
        else if(key<root->val) root->left=deleteNode(root->left,key);
        else{
            if(!root->left)return root->right;
            else if(!root->right)return root->left;
            TreeNode* node=root->right;
            while(node->left)node=node->left;
            node->left=root->left;
            root=root->right;
        }
        return root;
    }
};
相关推荐
炽烈小老头1 分钟前
【每天学习一点算法 2026/05/20】省份数量
学习·算法
乐迪信息2 分钟前
乐迪信息:港口夜间船舶巡查难,AI摄像机法全天候监测
人工智能·物联网·算法·计算机视觉·目标跟踪
sali-tec3 分钟前
C# 基于OpenCv的视觉工作流-章74-线-线距离
图像处理·人工智能·opencv·算法·计算机视觉
CryptoPP4 分钟前
快速集成:基于现代API的金融数据流解决方案
大数据·数据结构·笔记·金融·区块链
YL200404267 分钟前
054实现Trie(前缀树)
数据结构·leetcode
故事和你917 分钟前
洛谷-【图论2-3】最小生成树1
开发语言·数据结构·c++·算法·动态规划·图论
故事和你919 分钟前
洛谷-【图论2-3】最小生成树2
开发语言·数据结构·c++·算法·动态规划·图论
guygg8810 分钟前
贝叶斯非局部均值降噪算法C语言实现
c语言·算法·均值算法
量子炒饭大师11 分钟前
【优化算法】滑动窗口的「义体化」重构 ——【滑动窗口】何为滑动窗口?滑动窗口算法的核心目的是什么?
c++·算法·重构·优化算法·双指针·滑动窗口
玖釉-13 分钟前
C++ 中的 buckets 详解:从哈希桶到 unordered_map 底层原理
算法·哈希算法·散列表