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
79 lines (65 loc) · 1.44 KB
/
BreadthFirstTreeTraversal.js
File metadata and controls
79 lines (65 loc) · 1.44 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
🌳 Breadth-First Traversal (BFT) in JavaScript
🚀 Overview
Breadth-First Traversal visits nodes level by level from top to bottom using a queue (FIFO).
🧠 Intuition
Start at the root
Visit all nodes at current level
Move to next level
👉 Example:
1
/ \
2 3
/ \ \
4 5 6
BFT Output:
1 → 2 → 3 → 4 → 5 → 6
💻 Implementation in JavaScript
function bft(root) {
if (!root) return;
let queue = [root];
while (queue.length > 0) {
let node = queue.shift();
console.log(node.val);
if (node.left) queue.push(node.left);
if (node.right) queue.push(node.right);
}
}
🧪 Example Tree
class Node {
constructor(val) {
this.val = val;
this.left = null;
this.right = null;
}
}
// Create tree
let root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.right = new Node(6);
// Run
bft(root);
⚡ Optimized Version (Avoid shift)
function bftOptimized(root) {
if (!root) return;
let queue = [root];
let i = 0;
while (i < queue.length) {
let node = queue[i++];
console.log(node.val);
if (node.left) queue.push(node.left);
if (node.right) queue.push(node.right);
}
}
⏱ Complexity
Time: O(n)
Space: O(n)
🎯 When to Use BFT
Level order traversal
Finding shortest path in trees
Problems like:
Binary Tree Level Order Traversal
Minimum depth of tree
Right/Left view of tree