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

View File

@ -95,8 +95,13 @@ function remove(num) {
// 当子节点数量 = 0 / 1 时, child = null / 该子节点
let child = cur.left !== null ? cur.left : cur.right;
// 删除节点 cur
if (pre.left === cur) pre.left = child;
else pre.right = child;
if (cur != root) {
if (pre.left === cur) pre.left = child;
else pre.right = child;
} else {
// 若删除节点为根节点,则重新指定根节点
root = child;
}
}
// 子节点数量 = 2
else {