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

@ -109,10 +109,15 @@ class BinarySearchTree {
// 当子节点数量 = 0 / 1 时, child = null / 该子节点
TreeNode 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 {