Skip to content

Commit 870bca5

Browse files
committed
add: solve #250 Binary Tree Level Order Traversal with ts
1 parent f09e545 commit 870bca5

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/**
2+
* 이진 트리 노드의 정의입니다.
3+
* class TreeNode {
4+
* val: number;
5+
* left: TreeNode | null;
6+
* right: TreeNode | null;
7+
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
8+
* this.val = (val === undefined ? 0 : val);
9+
* this.left = (left === undefined ? null : left);
10+
* this.right = (right === undefined ? null : right);
11+
* }
12+
* }
13+
*/
14+
15+
/**
16+
* 이진트리 깊이별 노드 값들을 배열로 저장하는 함수.
17+
*
18+
* @param {TreeNode | null} root - 이진 트리의 루트 노드
19+
* @returns {number[][]} - 각 레벨별 노드 값들이 담긴 2차원 배열 반환
20+
*
21+
* 시간 복잡도: O(n)
22+
* - 모든 노드를 한 번씩 방문
23+
* 공간 복잡도: O(n)
24+
* - 재귀 호출 스택 및 결과 배열 사용
25+
*/
26+
function levelOrder(root: TreeNode | null): number[][] {
27+
// idx -> 각 깊이별 노드 값들을 저장
28+
const result: number[][] = [];
29+
30+
const dfs = (node: TreeNode | null, depth: number): void => {
31+
// 노드가 null이면 재귀 종료
32+
if (node === null) return;
33+
34+
// 현재 depth를 처음 방문되는 경우, 결과 배열에 새로운 depth 배열을 추가
35+
if (result.length === depth) {
36+
result.push([]);
37+
}
38+
39+
// 현재 노드의 값을 해당 레벨 배열에 추가
40+
result[depth].push(node.val);
41+
42+
// 왼쪽 자식 노드를 방문 (depth 1 증가시킴)
43+
dfs(node.left, depth + 1);
44+
// 오른쪽 자식 노드를 방문 (depth 1 증가시킴)
45+
dfs(node.right, depth + 1);
46+
}
47+
48+
// depth 0부터 탐색 시작
49+
dfs(root, 0);
50+
return result;
51+
};
52+

0 commit comments

Comments
 (0)