杨乐乐
Never too late

Follow

Never too late

Follow

Day 21 二叉树 - 二叉搜索树的最近公共祖先

杨乐乐's photo
杨乐乐
·Feb 5, 2023·

2 min read

Table of contents

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

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

function lowestCommonAncestor(root: TreeNode | null, p: TreeNode | null, q: TreeNode | null): TreeNode | null {
    if (root === null) {
        return root;
    }
    if (root.val > p.val && root.val > q.val) {
        return root.left = lowestCommonAncestor(root.left, p, q);
    } else if (root.val < p.val && root.val < q.val) {
        return root.right = lowestCommonAncestor(root.right, p, q);
    } else {
        return root;
    }
};

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

function insertIntoBST(root: TreeNode | null, val: number): TreeNode | null {
    if (root === null) {
        return new TreeNode(val);
    }

    if (root.val > val) {
        root.left = insertIntoBST(root.left, val);
    }

    if (root.val < val) {
        root.right = insertIntoBST(root.right, val)
    }

    return root;
};

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

function deleteNode(root: TreeNode | null, key: number): TreeNode | null {
    if (root === null) {
        return null;
    };

    if (root.val === key) {
        // 左右都为空
        if (root.left === null && root.right === null) {
            return null;
        }

        // 左为空,右不为空
        if (root.left === null && root.right !== null) {
            return root.right;
        }

        // 左不为空,右为空
        if (root.left !== null && root.right === null) {
            return root.left;
        }

        // 左右都不为空
        if (root.left !== null && root.right !== null) {
            let cur = root.right;
            while (cur.left) {
                cur = cur.left;
            }
            cur.left = root.left;
            return root.right;
        }
    }

    if (root.val < key) {
        root.right = deleteNode(root.right, key);
    }

    if (root.val > key) {
        root.left = deleteNode(root.left, key);
    }

    return root;
};
 
Share this