본문 바로가기

LeetCode

589. N-ary Tree Preorder Traversal / TypeScript

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].

이와 같은 방식으로 각 노드는 자신의 값을 가지고 있으며, 자식 노드들을 가리킴.