Skip to content

Commit 6ee5bee

Browse files
committed
Add week 7 solutions : binaryTreeLevelOrderTraversal
1 parent 1977bab commit 6ee5bee

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
// Time Complexity: O(n)
2+
// Space Complexity: O(n)
3+
4+
var levelOrder = function (root) {
5+
// if the root is null, return an empty array.
6+
if (root === null) return [];
7+
8+
const result = [];
9+
const queue = [root];
10+
11+
// while there are nodes in the queue,
12+
while (queue.length > 0) {
13+
const levelSize = queue.length;
14+
const currentLevel = [];
15+
16+
// loop nodes in the current level.
17+
for (let i = 0; i < levelSize; i++) {
18+
// dequeue the front node.
19+
const currentNode = queue.shift();
20+
// add value to the current level array.
21+
currentLevel.push(currentNode.val);
22+
// enqueue left child if exists.
23+
if (currentNode.left) queue.push(currentNode.left);
24+
// enqueue right child if exists.
25+
if (currentNode.right) queue.push(currentNode.right);
26+
}
27+
28+
// add the current level array to the result.
29+
result.push(currentLevel);
30+
}
31+
32+
return result;
33+
};

0 commit comments

Comments
 (0)