-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbfs-binarytree.js
More file actions
38 lines (33 loc) · 977 Bytes
/
Copy pathbfs-binarytree.js
File metadata and controls
38 lines (33 loc) · 977 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
// This is the Breadth First Traversal Algorithm
// To achieve this form of traversal we can use a queue (FIFO) data structure.
// 1. Initiate a queue with root in it.
// 2. Remove the first item out of queue
// 3. Push the left and right chidren of popped item into the queue
// 4. Repeat steps 2 and 3 until the queue is empty
function Node(value){
this.value = value
this.left = null
this.right = null
}
//usage
const root = new Node(2)
root.left = new Node(1)
root.right = new Node(3)
root.left.left = new Node(8)
root.left.right = new Node(10)
root.right.left = new Node(11)
root.right.right = new Node(15)
function walkBFS(root) {
if(root === null) return
const queue = [root]
console.log(queue.length)
while(queue.length){
const item = queue.shift()
//do something
console.log(item)
if(item.left) queue.push(item.left)
if(item.right) queue.push(item.right)
}
console.log(queue)
}
walkBFS(root)