代码随想录算法训练营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;
    }
};
相关推荐
421!2 分钟前
ESP32学习笔记之GPIO
开发语言·笔记·单片机·嵌入式硬件·学习·算法·fpga开发
夏日听雨眠6 分钟前
数据结构(单循环链表)
数据结构·链表
智算菩萨10 分钟前
【How Far Are We From AGI】4 AGI的“生理系统“——从算法架构到算力基座的工程革命
论文阅读·人工智能·深度学习·算法·ai·架构·agi
福赖12 分钟前
《算法:生产车间》
算法
alphaTao20 分钟前
LeetCode 每日一题 2026/3/16-2026/3/22
linux·windows·leetcode
空空潍21 分钟前
LeetCode力扣 hot100一刷完结
算法·leetcode
leaves falling24 分钟前
搜索插入位置(第一个≥target的位置)
算法
历程里程碑24 分钟前
41 .UDP -3 群聊功能实现:线程池助力多客户端通信
linux·开发语言·网络·数据结构·c++·网络协议·udp
lcreek24 分钟前
LeetCode 1162.地图分析
算法·leetcode·bfs
寒月小酒27 分钟前
3.20 OJ
算法