-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinarySearchTree.ts
97 lines (76 loc) · 2.78 KB
/
BinarySearchTree.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
class TreeNode {
public left: TreeNode | null = null;
public right: TreeNode | null = null;
constructor(public data: number) { }
}
class BinarySearchTree {
private root: TreeNode | null = null;
public insert = (value: number, root: TreeNode | null = this.root) : TreeNode => {
if (this.root === null) {
this.root = new TreeNode(value);
}
if (root === null) {
const node = new TreeNode(value);
return node;
}
if (value < root.data) {
root.left = this.insert(value, root.left);
}
if (value > root.data) {
root.right = this.insert(value, root.right);
}
return root;
}
public delete = () => {
// TODO : Implement
}
public contains = (value: number, node: TreeNode | null = this.root): boolean => {
if (this.root === null) {
return false;
}
if (node === null) return false;
if (node.data === value) return true;
return this.contains(value, node.left) || this.contains(value, node.right);
}
public search = (value: number, node: TreeNode | null = this.root): TreeNode | null => {
if (this.root === null) {
return null;
}
if (node === null) return null;
if (node.data === value) return node;
if (this.search(value, node.left)) {
return this.search(value, node.left);
}
if (this.search(value, node.right)) {
return this.search(value, node.right);
}
return null;
}
public inorderTraversal = (root: TreeNode | null = this.root): number[] => {
if (this.root === null) return [];
if (root === null) return [];
const left = this.inorderTraversal(root.left);
const right = this.inorderTraversal(root.right);
return [...left, root.data, ...right];
}
public preOrderTraversal = (root: TreeNode | null = this.root): number[] => {
if (this.root === null) return [];
if (root === null) return [];
const left = this.inorderTraversal(root.left);
const right = this.inorderTraversal(root.right);
return [root.data, ...left, ...right];
}
public postOrderTraversal = (root: TreeNode | null = this.root): number[] => {
if (this.root === null) return [];
if (root === null) return [];
const left = this.inorderTraversal(root.left);
const right = this.inorderTraversal(root.right);
return [...left, ...right, root.data];
}
}
/**********************************************************************************************************/
const BST = new BinarySearchTree();
BST.insert(8);
BST.insert(4);
BST.insert(12);
console.log(BST.postOrderTraversal());