-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheight.js
More file actions
81 lines (64 loc) · 1.18 KB
/
Copy pathheight.js
File metadata and controls
81 lines (64 loc) · 1.18 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
//Binary trees
//the tree constructor
function BST(){
this.root = null;
}
//Node constructor
function BTNode(value) {
this.val = value;
this.left = null;
this.right = null;
}
BST.prototype.add = function(val){
if(!this.root){
this.root = new BTNode(val)
return this;
}
var runner = this.root;
while(runner){
if(val < runner.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
}
}
}
myBST = new BST();
// console.log(myBST)
myBST.add(49).add(46).add(65).add(47).add(35).add(100).add(200).add(300)
myBST.add(5)
console.log(myBST)
BST.prototype.height = function (node = this.root)
if(!this.root){
return 0;
}
var height = 1;
// if(!node){
// node = this.root;
// }
if(!node.left && !node.right){
return 1 ;
}
var leftHeight;
var rightHeight;
if (node.left){
leftHeight = this.height(node.left) + 1;
}
if (node.right){
rightHeight = this.height(node.right) + 1;
}
if( leftHeight > rightHeight){
return leftHeight;
} else {
return rightHeight;
}
}
console.log(myBST.height())