forked from TheAlgorithms/JavaScript
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBreadthFirstTreeTraversal.js
More file actions
Latest commit
51 lines (45 loc) · 1.04 KB
/
Copy pathBreadthFirstTreeTraversal.js
File metadata and controls
51 lines (45 loc) · 1.04 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
/*
Breadth First Tree Traversal or level order traversal implementation in javascript
Author: @GerardUbuntu
*/
classNode{
constructor(data){
this.data=data
this.left=null
this.right=null
}
}
classBinaryTree{
constructor(){
this.root=null
this.traversal=[]
}
breadthFirst(){
consth=this.getHeight(this.root)
for(leti=0;i!==h;i++){
this.traverseLevel(this.root,i)
}
returnthis.traversal
}
// Computing the height of the tree
getHeight(node){
if(node===null){
return0
}
constlheight=this.getHeight(node.left)
constrheight=this.getHeight(node.right)
returnlheight>rheight ? lheight+1 : rheight+1
}
traverseLevel(node,levelRemaining){
if(node===null){
return
}
if(levelRemaining===0){
this.traversal.push(node.data)
}else{
this.traverseLevel(node.left,levelRemaining-1)
this.traverseLevel(node.right,levelRemaining-1)
}
}
}
export{BinaryTree,Node}