Fix remove() in binary search tree.

This commit is contained in:
krahets
2023-05-26 20:34:22 +08:00
parent ee716a2c23
commit b39e79be85
9 changed files with 111 additions and 50 deletions
+10 -4
View File
@@ -128,12 +128,18 @@ func (bst *binarySearchTree) remove(num int) {
} else {
child = cur.Right
}
// 将子节点替换为待删除节点
if pre.Left == cur {
pre.Left = child
// 删除节点 cur
if cur != bst.root {
if pre.Left == cur {
pre.Left = child
} else {
pre.Right = child
}
} else {
pre.Right = child
// 若删除节点为根节点,则重新指定根节点
bst.root = child
}
// 子节点数为 2
} else {
// 获取中序遍历中待删除节点 cur 的下一个节点