import {Color, TreeNode} from "./Node"; import {InsertHandler} from "./InsertHandler"; import {DeleteHandler} from "./DeleteHandler"; export interface NodeFactory { create(value: T, color: Color): TreeNode; } export class RedBlackTree { private readonly insertHandler: InsertHandler; private readonly deleteHandler: DeleteHandler; private root: TreeNode = null; private readonly comparator: (o1: T, o2: T) => number; constructor(nodeFactory: NodeFactory, comparator: (o1: T, o2: T) => number ) { this.insertHandler = new InsertHandler(this, nodeFactory, comparator); this.deleteHandler = new DeleteHandler(this, comparator); this.comparator = comparator; } delete(node: TreeNode): void { this.deleteHandler.delete(node); } insert(value: T): TreeNode { return this.insertHandler.insert(value); } findNode(value: T): TreeNode { if(this.root == null) { return null; } else { let nextNode = this.root; while(nextNode != null) { if(this.comparator(nextNode.getValue(), value) === 0) { return nextNode; } else { if(this.comparator(value,nextNode.getValue()) > 0) { nextNode = nextNode.getRightChild(); } else { nextNode = nextNode.getLeftChild(); } } } return null; } } getRoot(): TreeNode { return this.root; } hasRoot(): boolean { return this.root != null; } isRoot(node: TreeNode): boolean { return this.root === node; } setRoot(node: TreeNode): void { this.root = node; if(this.root != null) { this.root.setParent(null); } } }