Skip to content

Commit 0a731d2

Browse files
committed
Add binary-tree-level-order-traversal solution
1 parent 7268f40 commit 0a731d2

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
// ✅ Time Complexity: O(n), where n is the number of nodes in the tree
2+
// ✅ Space Complexity: O(n)
3+
4+
/**
5+
* Definition for a binary tree node.
6+
* function TreeNode(val, left, right) {
7+
* this.val = (val===undefined ? 0 : val)
8+
* this.left = (left===undefined ? null : left)
9+
* this.right = (right===undefined ? null : right)
10+
* }
11+
*/
12+
/**
13+
* @param {TreeNode} root
14+
* @return {number[][]}
15+
*/
16+
var levelOrder = function (root) {
17+
if (!root) return [];
18+
19+
let output = [];
20+
let queue = [root];
21+
22+
while (queue.length > 0) {
23+
let values = [];
24+
25+
const lengthQueue = queue.length;
26+
27+
for (let i = 0; i < lengthQueue; i++) {
28+
const node = queue.shift();
29+
values.push(node.val);
30+
if (node.left) queue.push(node.left);
31+
if (node.right) queue.push(node.right);
32+
}
33+
output.push(values);
34+
}
35+
return output;
36+
};
37+

0 commit comments

Comments
 (0)