-
Notifications
You must be signed in to change notification settings - Fork 0
/
LevelOrderSearch.js
59 lines (51 loc) · 992 Bytes
/
LevelOrderSearch.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
function BinaryTree(data){
this.root = new Node(data);
}
function Node(data){
this.data = data;
this.left = null;
this.right = null;
}
Node.prototype.insertLeft = function(data){
this.left = new Node(data);
return this.left;
}
Node.prototype.insertRight = function(data){
this.right = new Node(data);
return this.right;
}
Node.prototype.height = function(data){
if(this.left && this.right){
return 1+Math.max(this.left.height(),this.right.height());
}
else if(this.left){
return 1+ this.left.height();
}
else if(this.right){
return 1+ this.right.height();
}
else{
return 1;
}
}
function printLevelOrder(node){
if(node){
var height = node.height()
for(var i=1;i<=height;i++){
printGivenLevel(node,i);
}
}
return null;
}
function printGivenLevel(tree,level){
if(!tree){
return null;
}
else if(level === 1){
console.log(tree.data);
}
else{
printGivenLevel(tree.left,level-1);
printGivenLevel(tree.right,level-1);
}
}