代码随想录算法训练营第22天|二叉树part08

二叉搜索树公共祖先

    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    if(root.val > p.val && root.val > q.val) {
        return lowestCommonAncestor(root.left, p, q);
    } else if (root.val < p.val && root.val < q.val) {
        return lowestCommonAncestor(root.right, p, q);
    }
    return root;
}

二叉搜索树中的插入操作

    public TreeNode insertIntoBST(TreeNode root, int val) {
    if(root == null) {
        return new TreeNode(val);
    }
    if(root.val > val) {
        root.left = insertIntoBST(root.left, val);
    } else if(root.val < val) {
        root.right = insertIntoBST(root.right, val);
    }
    return root;
}

删除二叉搜索树中的节点

    public TreeNode deleteNode(TreeNode root, int key) {
    if(root == null) {
        return root;
    }
    if(root.val > key) {
        root.left = deleteNode(root.left, key);
    } else if(root.val < key) {
        root.right = deleteNode(root.right, key);
    } else {
        if(root.left == null) {
            return root.right;
        } else if(root.right == null) {
            return root.left;
        } else {
            TreeNode cur = root.right;
            while(cur.left != null) {
                cur = cur.left;
            }
            cur.left = root.left;
            return root.right;
        }
    }
    return root;
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容