Skip to content

Commit ecc65dd

Browse files
committed
solve: binary tree level order traversal
1 parent a43dd47 commit ecc65dd

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

binary-tree-level-order-traversal/wogha95.js

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,59 @@
1+
/**
2+
* 2차
3+
* 각 level의 node 수만큼 끊어서 순회하기
4+
*
5+
* TC: O(N)
6+
* SC: O(N)
7+
* N: total of nodes
8+
*/
9+
10+
/**
11+
* Definition for a binary tree node.
12+
* function TreeNode(val, left, right) {
13+
* this.val = (val===undefined ? 0 : val)
14+
* this.left = (left===undefined ? null : left)
15+
* this.right = (right===undefined ? null : right)
16+
* }
17+
*/
18+
/**
19+
* @param {TreeNode} root
20+
* @return {number[][]}
21+
*/
22+
var levelOrder = function (root) {
23+
if (!root) {
24+
return [];
25+
}
26+
27+
const result = [];
28+
const queue = [root];
29+
30+
while (queue.length > 0) {
31+
const level = queue.length;
32+
const currentLevelValList = [];
33+
34+
for (let i = 0; i < level; i++) {
35+
const current = queue.shift();
36+
37+
currentLevelValList.push(current.val);
38+
39+
if (current.left) {
40+
queue.push(current.left);
41+
}
42+
43+
if (current.right) {
44+
queue.push(current.right);
45+
}
46+
}
47+
48+
result.push(currentLevelValList);
49+
}
50+
51+
return result;
52+
};
53+
154
/**
255
* 1차
56+
* level과 노드를 queue에 추가해서 정답만들기
357
*
458
* TC: O(N)
559
* SC: O(N)

0 commit comments

Comments
 (0)