Skip to content

Commit a8b6f51

Browse files
committed
binary-tree-level-order-traversal
1 parent 3bdee5a commit a8b6f51

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* https://leetcode.com/problems/binary-tree-level-order-traversal/description/
3+
* Definition for a binary tree node.
4+
* function TreeNode(val, left, right) {
5+
* this.val = (val===undefined ? 0 : val)
6+
* this.left = (left===undefined ? null : left)
7+
* this.right = (right===undefined ? null : right)
8+
* }
9+
*/
10+
/**
11+
* @param {TreeNode} root
12+
* @return {number[][]}
13+
*/
14+
var levelOrder = function (root) {
15+
const result = [];
16+
if (!root) return result;
17+
18+
const queue = [root];
19+
20+
while (queue.length > 0) {
21+
const levelSize = queue.length;
22+
const level = [];
23+
24+
for (let i = 0; i < levelSize; i++) {
25+
const node = queue.shift();
26+
level.push(node.val);
27+
28+
if (node.left) queue.push(node.left);
29+
if (node.right) queue.push(node.right);
30+
}
31+
32+
result.push(level);
33+
}
34+
35+
return result;
36+
};

0 commit comments

Comments
 (0)