Skip to content

Commit 81d1a8f

Browse files
committed
binary-tree-level-order-traversal solution
1 parent ad72736 commit 81d1a8f

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
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+
var levelOrder = function (root) {
14+
if (!root) {
15+
return [];
16+
}
17+
18+
const queue = [root];
19+
const answer = [];
20+
21+
while (queue.length > 0) {
22+
const values = [];
23+
24+
const currentQueueLen = queue.length;
25+
26+
for (let i = 0; i < currentQueueLen; i++) {
27+
const head = queue.shift();
28+
29+
values.push(head.val);
30+
31+
head.left && queue.push(head.left);
32+
head.right && queue.push(head.right);
33+
}
34+
35+
answer.push(values);
36+
}
37+
38+
return answer;
39+
};
40+
41+
// ์‹œ๊ฐ„๋ณต์žก๋„ O(n) -> ๋ชจ๋“  ๋…ธ๋“œ๋ฅผ ํ•œ๋ฒˆ์”ฉ ๋„ˆ๋น„์šฐ์„ ํƒ์ƒ‰์œผ๋กœ ๋ฐฉ๋ฌธํ•˜๋ฏ€๋กœ
42+
// ๊ณต๊ฐ„๋ณต์žก๋„ O(n) -> ํ์— ๋ชจ๋“  ๋…ธ๋“œ์˜ ๊ฐ’์„ ์ €์žฅํ•˜๋ฏ€๋กœ

0 commit comments

Comments
ย (0)