Removes the given node, and returns the node that was physically removed from the tree.
(
node: BinarySearchNode<T>,
)
| 383 | |
| 384 | /** Removes the given node, and returns the node that was physically removed from the tree. */ |
| 385 | #removeNode( |
| 386 | node: BinarySearchNode<T>, |
| 387 | ): BinarySearchNode<T> | null { |
| 388 | /** |
| 389 | * The node to physically remove from the tree. |
| 390 | * Guaranteed to have at most one child. |
| 391 | */ |
| 392 | const flaggedNode: BinarySearchNode<T> | null = !node.left || !node.right |
| 393 | ? node |
| 394 | : node.findSuccessorNode()!; |
| 395 | /** Replaces the flagged node. */ |
| 396 | const replacementNode: BinarySearchNode<T> | null = flaggedNode.left ?? |
| 397 | flaggedNode.right; |
| 398 | |
| 399 | if (replacementNode) replacementNode.parent = flaggedNode.parent; |
| 400 | if (!flaggedNode.parent) { |
| 401 | this.#root = replacementNode; |
| 402 | } else { |
| 403 | flaggedNode.parent[flaggedNode.directionFromParent()!] = replacementNode; |
| 404 | } |
| 405 | if (flaggedNode !== node) { |
| 406 | /** Swaps values, in case value of the removed node is still needed by consumer. */ |
| 407 | const swapValue = node.value; |
| 408 | node.value = flaggedNode.value; |
| 409 | flaggedNode.value = swapValue; |
| 410 | } |
| 411 | |
| 412 | this.#size--; |
| 413 | return flaggedNode; |
| 414 | } |
| 415 | |
| 416 | /** |
| 417 | * Add a value to the binary search tree if it does not already exist in the |
no test coverage detected