MCPcopy Create free account
hub / github.com/denoland/std / #removeNode

Method #removeNode

data_structures/binary_search_tree.ts:385–414  ·  view source on GitHub ↗

Removes the given node, and returns the node that was physically removed from the tree.

(
    node: BinarySearchNode<T>,
  )

Source from the content-addressed store, hash-verified

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

Callers 2

removeMethod · 0.95
BinarySearchTreeClass · 0.80

Calls 2

findSuccessorNodeMethod · 0.80
directionFromParentMethod · 0.80

Tested by

no test coverage detected