码随想录Day22打卡 二叉树(7)

56 阅读1分钟

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

利用二叉搜索树有序的特性,我们可以直接比较p,q和root的值来判定

var lowestCommonAncestor = function(root, p, q) {
    if (root == null) return null
    // 因为我们要根据p和q的值来确定遍历哪边,所以要确保p小于q,便于后续处理
    if (p.val > q.val) {
        return lowestCommonAncestor(root, q, p)
    }
    // 如果p的值等于root的值或者q的值等于root的值,即证明root就是最近公共祖先
    if (p.val === root.val || q.val === root.val) {
        return root
    }
    // 如果p和q一个大于root另一个小于root,证明root是最近公共祖先
    if (p.val < root.val && q.val > root.val) {
        return root
    }
    // 最近公共祖先可能是左节点
    if (q.val < root.val) {
        return lowestCommonAncestor(root.left, p, q)
    }
    // 最近公共祖先可能是右节点
    if (p.val > root.val) {
        return lowestCommonAncestor(root.right, p, q)
    }
};

701 二叉树的插入操作

使用递归,这种解法代表插入的节点一定在叶子节点

var insertIntoBST = function(root, val) {
    // 当我们来到了一个叶子节点
    if (!root) {
        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 删除二叉搜索树中的节点

我们要分类讨论。

var deleteNode = function(root, key) {
    if (!root) return null
    if (root.val === key) {
        if (!root.left && !root.right) {
            return null
        } else if (!root.left) {
            return root.right
        } else if (!root.right) {
            return root.left
        } else {
            // 左右孩子节点都不为空,则将删除节点的左子树放到删除节点的右子树的最左面节点的左孩子的位置
            // 并返回删除节点右孩子为新的根节点
            let curr = root.right
            while (curr.left) {
                curr = curr.left
            }
            curr.left = root.left
            root = root.right
            return root
        }
    }
    if (root.val > key) {
        root.left = deleteNode(root.left, key)
    } 
    if (root.val < key) {
        root.right = deleteNode(root.right, key)
    }
    return root
};