-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathindex.ts
122 lines (99 loc) · 2.53 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
// import { add, find, remove } from "../binary-search-tree/index.ts";
import { Queue } from "../queue/index.ts";
// BINARY TREE is a non linear data structure where each node can have almost two child nodes.
// BINARY TREE is unordered hence slower in process of insertion, deletion and searching.
// IN BINARY TREE there is no ordering in terms of how the nodes are arranged
export function add<K, V>(root: BinaryTreeNode<K, V>, key: K, value?: V) {
console.log("Binary tree add", root, key);
const queue = new Queue<BinaryTreeNode<K, V>>();
queue.enqueue(root);
while (queue.size) {
root = queue.peek();
queue.dequeue();
if (!root.left) {
root.left = new BinaryTreeNode<K, V>(key, value);
break;
} else {
queue.enqueue(root.left);
}
if (!root.right) {
root.right = new BinaryTreeNode(key, value);
break;
} else {
queue.enqueue(root.right);
}
}
}
export function find<K, V>(
root: BinaryTreeNode<K, V> | undefined,
key: K
): BinaryTreeNode<K, V> | undefined {
if (!root) {
return;
}
if (root.key === key) {
return root;
}
const left = find(root.left, key);
return left ? left : find(root.right, key);
}
export interface BinaryTreeNode<K, V> {
key: K;
value?: V;
left?: BinaryTreeNode<K, V>;
right?: BinaryTreeNode<K, V>;
parent?: BinaryTreeNode<K, V>;
}
export class BinaryTreeNode<K, V> implements BinaryTreeNode<K, V> {
constructor(
key: K,
value?: V,
left?: BinaryTreeNode<K, V>,
right?: BinaryTreeNode<K, V>,
parent?: BinaryTreeNode<K, V>
) {
this.key = key;
this.value = value;
this.left = left;
this.right = right;
this.parent = parent;
}
// Insert
add(key: K, value?: V) {
return add(this, key, value);
}
// Search
find(key: K) {
return find(this, key);
}
// TODO: Delete
// Ref: https://www.geeksforgeeks.org/deletion-binary-tree
remove(key: K) {
// remove(this, key);
}
get grandparent() {
return this.parent?.parent;
}
get uncle() {
return this.parent?.sibling;
}
get sibling() {
if (!this?.parent) {
return;
}
if (this === this.parent.left) {
return this.parent.right;
} else {
return this.parent.left;
}
}
}
// // Initilise root node
// const root = new BinaryTreeNode(0);
// root.left = new BinaryTreeNode(1);
// root.left.left = new BinaryTreeNode(2);
// root.right = new BinaryTreeNode(3);
// root.right.right = new BinaryTreeNode(4);
// console.log(root.find(3));
// root.add(5);
// console.log(root);