UNPKG

1.29 kBPlain TextView Raw
1import { AbstractSet } from "../interface/AbstractSet";
2import { BasicBinaryTree } from "../tree/basic-binary-tree/BasicBinaryTree";
3import { RedBlackTree } from "../tree/red-black-tree/RedBlackTree";
4
5export class TreeSet<T> extends AbstractSet<T>{
6 private tree: RedBlackTree<T>;
7 private size = 0;
8 constructor(compareKey?: keyof T){
9 super();
10 this.tree = new RedBlackTree<T>(compareKey);
11 }
12 add(item: T): this {
13 if (this.tree.contains(item)){
14 return this;
15 }
16 this.tree.insert(item);
17 this.size++;
18 return this;
19 }
20 entries(): Array<T> {
21 return BasicBinaryTree.inTraversal(this.tree.Root);
22 }
23 has(item: T): boolean {
24 return this.tree.contains(item);
25 }
26 remove(item: T): boolean {
27 if (!this.tree.contains(item)){
28 return false;
29 }
30 this.size--;
31 return this.tree.remove(item);
32 }
33
34 diff(set: AbstractSet<T>): Array<T>{ // A-B 差集
35 return super.diff(set);
36 }
37
38 union(set: AbstractSet<T>): Array<T>{ // 并集
39 return super.union(set);
40 }
41
42 intersect(set: AbstractSet<T>): Array<T>{ // 交集
43 return super.intersect(set);
44 }
45
46 get Size(){
47 return this.size;
48 }
49}