-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinaryTree.ts
More file actions
83 lines (62 loc) · 2.25 KB
/
binaryTree.ts
File metadata and controls
83 lines (62 loc) · 2.25 KB
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
class TreeNode {
pointerLeft: TreeNode | null = null;
pointerRight: TreeNode | null = null;
constructor(public value: string) {}
}
class SearchBinaryTree {
current: TreeNode | null = null;
insertArray(arrayValues: string[]) {
arrayValues.forEach(
(value) => {
const newTreeNode = new TreeNode(value);
if (!this.current) {
this.current = newTreeNode;
return;
}
let currentTreeNode = this.current;
while (true) {
if (value === currentTreeNode.value) {
console.log(`${value} existe na arvore`);
return;
}
if (value < currentTreeNode.value) {
if (!currentTreeNode.pointerLeft) {
currentTreeNode.pointerLeft = newTreeNode;
console.log(`Inserido ${value} a esquerda do ${currentTreeNode.value}`);
return;
}
currentTreeNode = currentTreeNode.pointerLeft;
} else {
if (!currentTreeNode.pointerRight) {
currentTreeNode.pointerRight = newTreeNode;
console.log(`Inserido ${value} a direita do ${currentTreeNode.value}`);
return;
}
currentTreeNode = currentTreeNode.pointerRight;
}
}
}
);
}
search(value: string): boolean {
let currentTreeNode = this.current;
while (currentTreeNode) {
if (value === currentTreeNode.value) {
console.log(`${value} foi encontrado na arvore`);
return true;
}
currentTreeNode = value < currentTreeNode.value ? currentTreeNode.pointerLeft : currentTreeNode.pointerRight;
}
console.log(`${value} nao foi encontrado na arvore`);
return false;
}
}
const binaryTree = new SearchBinaryTree();
let arrayBinaryTree: string[] = ["Erik", "Ferri", "Liz"];
binaryTree.insertArray(arrayBinaryTree);
console.log("------------------")
binaryTree.search("Erik"); // true
binaryTree.search("Ferri"); // true
binaryTree.search("Liz"); // true
binaryTree.search("ferri"); // false
binaryTree.search("Zeca"); // false