하나의 n-ary 트리가 있다고 가정하고 해당 노드의 선주문 순회를 찾아야 합니다.
따라서 입력이 다음과 같으면

그러면 출력은 [1,3,5,6,2,4]
가 됩니다.이 문제를 해결하기 위해 다음 단계를 따릅니다. −
-
배열 정의
-
preorder()라는 메서드를 정의하면 루트가 됩니다.
-
루트가 null이면 -
-
빈 목록 반환
-
-
ans
끝에 root 값 삽입 -
루트의 자식 배열에 있는 모든 자식 i에 대해
-
선주문(i)
-
-
반환
예시
더 나은 이해를 위해 다음 구현을 살펴보겠습니다. −
#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v){
cout << "[";
for(int i = 0; i<v.size(); i++){
cout << v[i] << ", ";
}
cout << "]"<<endl;
}
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&g; ans;
vector<int> preorder(Node* root) {
if (!root)
return {};
ans.emplace_back(root->val);
for (auto i : root->children)
preorder(i);
return ans;
}
};
main(){
Solution ob;
Node *node5 = new Node(5), *node6 = new Node(6);
vector<Node*> child_of_3 = {node5, node6};
Node* node3 = new Node(3, child_of_3);
Node *node2 = new Node(2), *node4 = new Node(4);l
vector<Node*> child_of_1 = {node3, node2, node4};
Node *node1 = new Node(1, child_of_1);
print_vector(ob.preorder(node1));
} 입력
Node *node5 = new Node(5), *node6 = new Node(6);
vector<Node*> child_of_3 = {node5, node6};
Node* node3 = new Node(3, child_of_3);
Node *node2 = new Node(2), *node4 = new Node(4);
vector<Node*> child_of_1 = {node3, node2, node4};
Node *node1 = new Node(1, child_of_1); 출력
[1, 3, 5, 6, 2, 4, ]