Skip to content

Commit 86d8abb

Browse files
committed
이진 트리 레벨 순서 순회
1 parent fff83de commit 86d8abb

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+
* Definition for a binary tree node.
3+
* function TreeNode(val, left, right) {
4+
* this.val = (val===undefined ? 0 : val)
5+
* this.left = (left===undefined ? null : left)
6+
* this.right = (right===undefined ? null : right)
7+
* }
8+
*/
9+
/**
10+
* @param {TreeNode} root
11+
* @return {number[][]}
12+
*/
13+
function levelOrder(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 levelNodes = [];
22+
23+
for (let i = 0; i < levelSize; i++) {
24+
const node = queue.shift();
25+
levelNodes.push(node.val);
26+
27+
if (node.left) queue.push(node.left);
28+
if (node.right) queue.push(node.right);
29+
}
30+
31+
result.push(levelNodes);
32+
}
33+
34+
return result;
35+
};
36+

0 commit comments

Comments
 (0)