235.二叉搜索树的最近公共祖先、701.二叉搜索树的插入操作、450.删除二叉搜索树中的节点

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

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

题目链接

提交代码

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

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

题目链接

提交代码(方法)

class Solution {
public:
    TreeNode* insertIntoBST(TreeNode* root, int val) {
        TreeNode* node = new TreeNode(val);
        if(root == nullptr) return node;
        if(root -> val > val) root -> left = insertIntoBST(root -> left, val);
        else root -> right = insertIntoBST(root -> right, val);
        return root;
    }
};

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

题目链接

提交代码(方法)

class Solution {
public:
    TreeNode* deleteNode(TreeNode* root, int key) {
        if(root == nullptr) return root;
        if(root -> val == key)
        {
            if(root -> left == nullptr && root -> right == nullptr) return nullptr;
            if(root -> left == nullptr && root -> right != nullptr) return root -> right;
            else if(root -> left != nullptr && root -> right == nullptr) return root -> left;
            else{
                TreeNode* cur = root -> right;
                while(cur -> left) cur = cur -> left;
                cur ->left = root ->left;
                return root -> right; 
            }
        }
        root -> left = deleteNode(root -> left, key);
        root -> right = deleteNode(root ->right, key);
        return root;
    }
};

总结

                     日期: 2023 年 4 月 4 日
              学习时长: 0 h 30 m
                     难度: ★ \bigstar
累计完成题目数量: 60
距离目标还有数量: 240
                      小结:

你可能感兴趣的:(leetcode,算法,贪心算法)