Skip to content

Commit 318ff27

Browse files
committed
Add Level Order Traversal algorithm with Vitest tests
1 parent b8f2105 commit 318ff27

File tree

4 files changed

+458
-248
lines changed

4 files changed

+458
-248
lines changed

Trees/LevelOrderTraversal.js

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* Level Order Traversal of a Binary Tree (Breadth-First Traversal)
3+
*/
4+
5+
export class Node {
6+
constructor(value) {
7+
this.value = value;
8+
this.left = null;
9+
this.right = null;
10+
}
11+
}
12+
13+
export function levelOrderTraversal(root) {
14+
if (!root) return [];
15+
16+
const result = [];
17+
const queue = [root];
18+
19+
while (queue.length > 0) {
20+
const levelSize = queue.length;
21+
const currentLevel = [];
22+
23+
for (let i = 0; i < levelSize; i++) {
24+
const node = queue.shift();
25+
currentLevel.push(node.value);
26+
27+
if (node.left) queue.push(node.left);
28+
if (node.right) queue.push(node.right);
29+
}
30+
31+
result.push(currentLevel);
32+
}
33+
34+
return result;
35+
}
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import { Node, levelOrderTraversal } from "../LevelOrderTraversal.js";
2+
3+
describe("Level Order Traversal", () => {
4+
test("should return empty array for empty tree", () => {
5+
expect(levelOrderTraversal(null)).toEqual([]);
6+
});
7+
8+
test("should return single node tree", () => {
9+
const root = new Node(1);
10+
expect(levelOrderTraversal(root)).toEqual([[1]]);
11+
});
12+
13+
test("should return correct level order for complete tree", () => {
14+
const root = new Node(1);
15+
root.left = new Node(2);
16+
root.right = new Node(3);
17+
root.left.left = new Node(4);
18+
root.left.right = new Node(5);
19+
root.right.left = new Node(6);
20+
root.right.right = new Node(7);
21+
22+
expect(levelOrderTraversal(root)).toEqual([[1], [2, 3], [4, 5, 6, 7]]);
23+
});
24+
25+
test("should handle unbalanced tree", () => {
26+
const root = new Node(1);
27+
root.left = new Node(2);
28+
root.left.left = new Node(3);
29+
30+
expect(levelOrderTraversal(root)).toEqual([[1], [2], [3]]);
31+
});
32+
});

0 commit comments

Comments
 (0)