-
Notifications
You must be signed in to change notification settings - Fork 0
/
27-depth-first-search.js
97 lines (86 loc) · 2.36 KB
/
27-depth-first-search.js
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 Node {
constructor(value) {
this.left = null;
this.value = value;
this.right = null;
}
}
class BinarySearchTree {
constructor() {
this.root = null;
}
insert(value) {
let newNode = new Node(value);
if (!this.root) {
this.root = newNode;
return this;
}
let currentNode = this.root;
while (currentNode) {
if (currentNode.value > newNode.value) {
if (!currentNode.left) {
currentNode.left = newNode;
return this;
}
currentNode = currentNode.left;
} else {
if (!currentNode.right) {
currentNode.right = newNode;
return this;
}
currentNode = currentNode.right;
}
}
}
lookup(value) {
if (!this.root) return false;
let currentNode = this.root;
while (currentNode) {
if (currentNode.value == value) return true;
else if (currentNode.value < value) {
currentNode = currentNode.left;
} else {
currentNode = currentNode.right;
}
}
return false;
}
inOrderDepthFirstSearch() {
return this.inOrderTraverse(this.root, []);
}
inOrderTraverse(currentNode, list) {
if (currentNode.left) this.inOrderTraverse(currentNode.left, list);
list.push(currentNode.value);
if (currentNode.right) this.inOrderTraverse(currentNode.right, list);
return list;
}
preOrderDepthFirstSearch() {
return this.preOrderTraverse(this.root, []);
}
preOrderTraverse(currentNode, list) {
list.push(currentNode.value);
if (currentNode.left) this.preOrderTraverse(currentNode.left, list);
if (currentNode.right) this.preOrderTraverse(currentNode.right, list);
return list;
}
postOrderDepthFirstSearch() {
return this.postOrderTraverse(this.root, []);
}
postOrderTraverse(currentNode, list) {
if (currentNode.left) this.postOrderTraverse(currentNode.left, list);
if (currentNode.right) this.postOrderTraverse(currentNode.right, list);
list.push(currentNode.value);
return list;
}
}
let tree = new BinarySearchTree();
tree.insert(9);
tree.insert(4);
tree.insert(6);
tree.insert(20);
tree.insert(170);
tree.insert(15);
tree.insert(1);
console.log("InOrder DFS: ", tree.inOrderDepthFirstSearch());
console.log("PreOrder DFS: ", tree.preOrderDepthFirstSearch());
console.log("PostOrder DFS: ", tree.postOrderDepthFirstSearch());