-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_search_tree.js
More file actions
64 lines (54 loc) · 1.19 KB
/
binary_search_tree.js
File metadata and controls
64 lines (54 loc) · 1.19 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
// Binary Search
class Node{
constructor(val){
this.val = val;
this.left = null;
this.right = null;
}
}
class BST{
constructor(){
this.root = null;
}
}
BST.prototype.insert = function(val, node){
if(!this.root){
this.root = new Node(val);
return this;
}
node = node || this.root
if(val < node.val){
node.left ? this.insert(val, node.left) : node.left = new Node(val);
}
else{
node.right ? this.insert(val, node.right) : node.right = new Node(val);
}
return this;
}
BST.prototype.preorder = function(node){
if(!node){
return;
}
console.log(node.val);
this.preorder(node.left);
this.preorder(node.right);
}
BST.prototype.inorder = function(node){
if(node){
this.inorder(node.left);
console.log(node.val);
this.inorder(node.right);
}
return this;
}
BST.prototype.postorder = function(node){
if(node){
this.postorder(node.left);
this.postorder(node.right);
console.log(node.val);
}
return this;
}
var bst = new BST();
bst.insert(5).insert(2).insert(9).insert(1).insert(4);
bst.preorder(bst.root);