/** This module is browser compatible. */ export type direction = "left" | "right"; export class BSNode { left: BSNode | null; right: BSNode | null; constructor(public parent: BSNode | null, public value: T) { this.left = null; this.right = null; } static from(node: BSNode): BSNode { const copy: BSNode = new BSNode(node.parent, node.value); copy.left = node.left; copy.right = node.right; return copy; } directionFromParent(): direction | null { return this.parent === null ? null : this === this.parent.left ? "left" : this === this.parent.right ? "right" : null; } findMinNode(): BSNode { let minNode: BSNode | null = this.left; while (minNode?.left) minNode = minNode.left; return minNode ?? this; } findMaxNode(): BSNode { let maxNode: BSNode | null = this.right; while (maxNode?.right) maxNode = maxNode.right; return maxNode ?? this; } findSuccessorNode(): BSNode | null { if (this.right !== null) return this.right.findMinNode(); let parent: BSNode | null = this.parent; let direction: direction | null = this.directionFromParent(); while (parent && direction === "right") { direction = parent.directionFromParent(); parent = parent.parent; } return parent; } }