Given the root of an n-ary tree, return the preorder traversal of its nodes' values.
Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples)
Example 1:

Input: root = [1,null,3,2,4,null,5,6]
Output: [1,3,5,6,2,4]
Example 2:

Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
Output: [1,2,3,6,7,11,14,4,8,12,5,9,13,10]
출처 :https://leetcode.com/problems/n-ary-tree-preorder-traversal/description/
풀이
function preorder(root: Node | null): number[] {
if (!root) return []
let ans: number[] = [root.val]
if (root.children) {
for (let child of root.children) {
ans = ans.concat(preorder(child))
}
}
return ans
};
1
/ | \
2 3 4
|
5
- 루트 노드 1의 값을 먼저 배열에 추가: [1]
- 루트 노드의 자식 노드들을 순서대로 :
- 노드 2를 방문하면: [1, 2]
- 노드 3을 방문하면: [1, 2, 3]
- 노드 3의 자식 노드 5를 방문하면: [1, 2, 3, 5]
- 노드 4를 방문하면: [1, 2, 3, 5, 4]
최종 반환 값은 [1, 2, 3, 5, 4]
이 구조에서 root.val은 1이고, root.children은 [child1, child2, child3].
child2.val은 3이고, child2.children은 [child4].
이와 같은 방식으로 각 노드는 자신의 값을 가지고 있으며, 자식 노드들을 가리킴.
'LeetCode' 카테고리의 다른 글
| 1407. Top Travellers (0) | 2024.06.03 |
|---|---|
| 1672. Richest Customer Wealth / TypeScript (1) | 2024.06.02 |
| 2629. Function Composition / TypeScript (0) | 2024.05.31 |
| 2566. Maximum Difference by Remapping a Digit / TypeScript (0) | 2024.05.30 |
| 2293. Min Max Game / TypeScript (0) | 2024.05.29 |