diff --git a/problems/0450.删除二叉搜索树中的节点.md b/problems/0450.删除二叉搜索树中的节点.md index e8f7e54c..8367a145 100644 --- a/problems/0450.删除二叉搜索树中的节点.md +++ b/problems/0450.删除二叉搜索树中的节点.md @@ -582,7 +582,35 @@ function deleteNode(root: TreeNode | null, key: number): TreeNode | null { }; ``` +## Scala +```scala +object Solution { + def deleteNode(root: TreeNode, key: Int): TreeNode = { + if (root == null) return root // 第一种情况,没找到删除的节点,遍历到空节点直接返回 + if (root.value == key) { + // 第二种情况: 左右孩子都为空,直接删除节点,返回null + if (root.left == null && root.right == null) return null + // 第三种情况: 左孩子为空,右孩子不为空,右孩子补位 + else if (root.left == null && root.right != null) return root.right + // 第四种情况: 左孩子不为空,右孩子为空,左孩子补位 + else if (root.left != null && root.right == null) return root.left + // 第五种情况: 左右孩子都不为空,将删除节点的左子树头节点(左孩子)放到 + // 右子树的最左边节点的左孩子上,返回删除节点的右孩子 + else { + var tmp = root.right + while (tmp.left != null) tmp = tmp.left + tmp.left = root.left + return root.right + } + } + if (root.value > key) root.left = deleteNode(root.left, key) + if (root.value < key) root.right = deleteNode(root.right, key) + + root // 返回根节点,return关键字可以省略 + } +} +``` -----------------------