/*
* @lc app=leetcode.cn id=450 lang=typescript
*
* [450] 删除二叉搜索树中的节点
*/
// @lc code=start
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
// @lc code=end
function deleteNode(root: TreeNode | null, key: number): TreeNode | null {
if (!root) return root
if (root.val === key && !root.left && !root.right) return null
const dfs = (node: TreeNode | null): TreeNode | null => {
if (!node) return node
if (node.val < key) {
node.right = dfs(node.right)
} else if (node.val > key) {
node.left = dfs(node.left)
} else {
// 找到等于 key 的结点,进行删除操作
// 如果存在右结点,则找到大于 key 的最小值来替换 key
// 如果不存在右结点,但存在左节点,则找到小于 key 的最小值来替换 key
// 如果左右结点都不存在,则说明当前结点为叶子结点,可以直接删除
if (node.right) {
// 存在右结点
if (!node.right.left) {
node.right.left = node.left
return node.right
}
const queue = [[node.right, node]]
for (let [child, parent] of queue) {
if (child.left) {
queue.push([child.left, child])
} else {
node.val = child.val
parent.left = child.right
return node
}
}
} else if (node.left) {
// 不存在右结点,但存在左节点
if (!node.left.right) {
node.left.right = node.right
return node.left
}
const queue = [[node.left, node]]
for (let [child, parent] of queue) {
if (child.right) {
queue.push([child.right, child])
} else {
node.val = child.val
parent.right = child.left
return node
}
}
} else {
// 左右子结点都不存在
return null
}
}
return node
}
return dfs(root)
}
test.each([
{ input: { root: [5, 3, 6, 2, 4, null, 7], key: 3 }, output: [5, 4, 6, 2, null, null, 7] },
{ input: { root: [5, 3, 6, 2, 4, null, 7], key: 0 }, output: [5, 3, 6, 2, 4, null, 7] },
{ input: { root: [], key: 0 }, output: [] },
])('input: root = $input.root, key = $input.key', ({ input: { root, key }, output }) => {
expect(deleteNode(BinaryTree.deserialize(root), key)).toEqual(BinaryTree.deserialize(output))
})