본문 바로가기

Algorithm/자료구조

(C++) - LeetCode (easy) 589. N-ary Tree Preorder Traversal

반응형

https://leetcode.com/problems/n-ary-tree-preorder-traversal/description/

 

N-ary Tree Preorder Traversal - LeetCode

Can you solve this real interview question? N-ary Tree Preorder Traversal - 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 chil

leetcode.com

pre order를 다진 tree에 대해 수행하는 문제였습니다.

📕 풀이방법

📔 풀이과정

재귀적으로 수행해줍니다.

1. 기저 case에서는 root가 NULL일 때 빈 vector를 반환합니다.

2. vector ans를 선언해 현재 val인 root->val을 push_back합니다.

3. children의 node에 대해서 for loop를 수행하며 재귀적으로 다음 자식 node에 대해 preoder함수를 수행합니다.

📔 정답 출력 | 반환

ans를 반환합니다.


📕 Code

📔 C++

/*
// Definition for a Node.
class Node {
public:
    int val;
    vector<Node*> children;

    Node() {}

    Node(int _val) {
        val = _val;
    }

    Node(int _val, vector<Node*> _children) {
        val = _val;
        children = _children;
    }
};
*/

class Solution {
public:
    vector<int> preorder(Node* root) {
        if(root == NULL) return vector<int>();
        vector <int> ans;
        ans.push_back(root->val);
        for(auto c : root->children) {
            vector <int> a = preorder(c);
            ans.insert(ans.end(), a.begin(), a.end());
        }
        return ans;
    }
};

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.