算法第十九天|二叉树

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

 public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        // 二叉搜索树的特点是根节点的值大于左子树,同时小于右子树
        // 后序遍历
        // 如果当前节点的值大于等于pq其中某一个,同时小于等于pq中的某一个
        // 因为是后续遍历,是从下网上,那么说明就找到了这个节点

        if (root.val > p.val && root.val > q.val) { // 同时大于两个节点的值,说明这两个节点都在该节点的左子树上
            return lowestCommonAncestor(root.left, p, q); // 只遍历其左子树即可,答案一定在它的左子树上
        }

        if (root.val < p.val && root.val < q.val) { // 同时小于两个节点的值,说明这两个节点都在该节点的右子树上
            return lowestCommonAncestor(root.right, p, q);
        }

        // 除此之外的结果,就是当前值是结果
        return root;
    }

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

    public TreeNode insertIntoBST(TreeNode root, int val) {
        if (root == null) {
            return new TreeNode(val);
        }
        // 二叉搜索树,根节点比左子树的都大,比右子树的都小
        // 所有值 Node.val 是 独一无二 的。
        TreeNode cur = root;
        insertIntoRoot(cur, val);
        return root;
    }

    private void insertIntoRoot(TreeNode cur, int val) {
        if (cur.val > val) {
            if (cur.left != null) {
                insertIntoRoot(cur.left, val);
            } else {
                cur.left = new TreeNode(val);
                return;
            }
        }

        if (cur.val < val) {
            if (cur.right != null) {
                insertIntoRoot(cur.right, val);
            } else {
                cur.right = new TreeNode(val);
                return;
            }
        }
    }

当前节点大于给定值,那么说明答案在左子树

当前节点小于给定值,那么说答案在右子树

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

 public TreeNode deleteNode(TreeNode root, int key) {
        if (root == null) {
            return null;
        }
        if (root.val == key) {
            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;
                root = root.right;
                return root;
            }
        } else {
            if (root.val > key) {
                root.left = deleteNode(root.left, key);
            } else {
                root.right = deleteNode(root.right, key);
            }
        }
        return root;
    }

当左右子树都有值的时候,需要将当前的左子树放入右子树的最左边叶子节点的左节点

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容