-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBST.js
More file actions
43 lines (40 loc) · 743 Bytes
/
Copy pathBST.js
File metadata and controls
43 lines (40 loc) · 743 Bytes
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
//Binary trees
//the tree constructor
function BST(){
this.root = null;
}
//Node constructor
function BTNode(value) {
this.val = value;
this.left = null;
this.right = null;
}
var myBST = new BST();
console.log(myBST)
//add new node to the Binary search tree:
BST.prototype.add = function (val ) {
if(!this.root){
this.root = new BTNode(val);
return this;
}
var runner = this.root;
while(runner){
if(runner.val > val) {
if(!runner.left){
runner.left = new BTNode(val);
return this;
}
runner = runner.left;
}
else {
if(!runner.right){
runner.right = new BTNode(val);
return this;
}
runner = runner.right;
}
}
}
//testing
myBST.add(5).add(10).add(4).add(10);
console.log("My BSt", myBST)