-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinarySearchTree.js
More file actions
105 lines (104 loc) · 2.55 KB
/
binarySearchTree.js
File metadata and controls
105 lines (104 loc) · 2.55 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
class Node{
constructor(val){
this.val = val;
this.right = null;
this.left = null;
}
}
class BST{
constructor(){
this.root = null;
}
insert(val){
var newNode = new Node(val);
if(!this.root){
this.root = newNode;
return this;
}
var current = this.root;
while(true){
if(current.val === val) return undefined;
if(current.val > val){
if(!current.left){
current.left = newNode;
return this;
}
current = current.left;
}else{
if(!current.right){
current.right = newNode;
return this;
}
current = current.right;
}
}
}
find(val){
if(!this.root){
return undefined;
}
var current = this.root;
while(current){
if(current.val === val) return true;
if(current.val> val){
current = current.left;
}else{
current = current.right;
}
}
return false;
}
BFS(){
var node = this.root,
data = [],
que = [];
que.push(node);
while(que.length){
node = que.shift();
data.push(node.val);
if(node.right) que.push(node.right);
if(node.left) que.push(node.left);
}
return data;
}
DFSPreOrder(){
var data = [];
function treverse(node){
data.push(node.val);
if(node.left) treverse(node.left);
if(node.right) treverse(node.right);
}
treverse(this.root);
return data;
}
DFSPostOrder(){
var data = [];
function treverse(node){
if(node.left) treverse(node.left);
if(node.right) treverse(node.right);
data.push(node.val);
}
treverse(this.root);
return data;
}
DFSInOrder(){
var data = [];
function treverse(node){
if(node.left) treverse(node.left);
data.push(node.val);
if(node.right) treverse(node.right);
}
treverse(this.root);
return data;
}
}
var tree = new BST();
tree.insert(10);
tree.insert(5);
tree.insert(15);
tree.insert(7);
tree.insert(1);
console.log(tree.BFS());
console.log(tree.DFSPreOrder());
console.log(tree.DFSPostOrder());
console.log(tree.DFSInOrder());