본문 바로가기

Algorithm/자료구조

(C++) - LeetCode (easy) 590. N-ary Tree Postorder Traversal

반응형

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

 

N-ary Tree Postorder Traversal - LeetCode

Can you solve this real interview question? N-ary Tree Postorder Traversal - Given the root of an n-ary tree, return the postorder traversal of its nodes' values. Nary-Tree input serialization is represented in their level order traversal. Each group of ch

leetcode.com

n진 tree의 후위순회를 하는 문제였습니다.

📕 풀이방법

📔 풀이과정

후위 순회는 자식을 먼저 방문한 뒤 마지막에 부모 node를 방문하면 됩니다.이를 재귀적으로 짜면 다음과 같습니다.1. 기저 case에서 현재 node가 NULL이면 빈 vector를 반환합니다.2. 정답 vector ans를 선언해줍니다.3. 현재 node의 child를 for loop로 수행하며 재귀 호출을 해줍니다. 그 결과를 vector child를 선언해 저장해줍니다.  3-1. ans의 끝에 child를 순회한 결과를 insert해줍니다.4. 현재 root의 val을 ans에 push_back해줍니다.5. 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> postorder(Node* root) {
        if(root == NULL) return vector<int>();
        vector <int> ans;
        for(auto c : root->children) {
            vector<int>child= postorder(c);
            ans.insert(ans.end(), child.begin(), child.end());
        }

        ans.push_back(root->val);

        return ans;
    }
};

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