代码随想录算法训练营第二十二天 | 235.二叉搜索树的最近公共祖先 701.二叉搜索树中的插入操作 450.删除二叉搜索树中的节点

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

题目链接 文章讲解 视频讲解

思路:递归遍历二叉搜索树
   如果当前值大于p和q的值,向左遍历
   如果当前值小于p和q的值,向右遍历
   否则说明当前值介于p和q之间,直接返回当前节点

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(root == nullptr) return nullptr;
        if(root->val > p->val && root->val > q->val) {
            TreeNode* left = lowestCommonAncestor(root->left, p, q);
            if(left) return left;
        }
        if(root->val < p->val && root->val < q->val) {
            TreeNode*right = lowestCommonAncestor(root->right, p, q);
            if(right) return right;
        }
        return root;
    }
};

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

题目链接 文章讲解 视频讲解

思路:遍历至空节点插入即可

class Solution {
public:
    TreeNode* insertIntoBST(TreeNode* root, int val) {
        if(root == nullptr) {
            root = new TreeNode(val);
            return root;
        }
        insert(root, val);
        return root;
    }
    void insert(TreeNode* node, int val) {
        // 当前节点大于插入值,向左遍历
        if(node->val > val) {
            if(node->left) insertIntoBST(node->left, val);
            else node->left = new TreeNode(val);
        }
        // 当前节点小于插入值,向右遍历
        if(node->val < val) {
            if(node->right) insertIntoBST(node->right, val);
            else node->right = new TreeNode(val);         
        }
        return ;
    }
};

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

题目链接 文章讲解 视频讲解

难点:当待删除的节点的左右子树都不为空时:
   将当前节点的左子树挂载到右子树的最左边;
   然后将当前指针指向当前节点的右子树。

class Solution {
public:
    TreeNode* deleteNode(TreeNode* root, int key) {
        // 1.如果根节点为空,或者没有找到key,直接返回nullptr
        if(root == nullptr) return nullptr;
        // 如果找到key
        if(root->val == key) {
            // 2.如果待删除节点的左右孩子都为空,直接删除节点返回nullptr 
            if(!root->left && !root->right) {
                delete root;
                return nullptr;
            }
            // 3.如果待删除节点左孩子不为空,右孩子为空
            else if(root->left && !root->right) {
                TreeNode* tem = root->left;
                delete root;
                return tem;
            }
            // 4.如果待删除节点的右孩子不空,左孩子为空
            else if(!root->left && root->right) {
                TreeNode* tem = root->right;
                delete root;
                return tem;
            }
            // 5.如果待删除节点的左右孩子都不为空
            else {
                TreeNode* tem = root;
                TreeNode* cur = root->right;
                while(cur->left) cur = cur->left;
                cur->left = root->left;            
                root = root->right;
                delete tem;
                return root;
            }
        }
        if(root->val > key) {
            root->left = deleteNode(root->left, key);
        }
        if(root->val < key) {
            root->right = deleteNode(root->right, key);
        }
        return root;
    }
};
posted @ 2024-06-03 14:05  深蓝von  阅读(2)  评论(0编辑  收藏  举报