-
Notifications
You must be signed in to change notification settings - Fork 1
/
589-N-ary-Tree-Preorder-Traversal.cpp
53 lines (41 loc) · 1.15 KB
/
589-N-ary-Tree-Preorder-Traversal.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/*
// 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) {
vector<int> ans;
if(!root) return ans;
traverse(root, ans);
return ans;
}
void traverse(Node* root, vector<int>& ans){
if(!root) return;
ans.push_back(root->val);
for(auto child : root->children){
traverse(child, ans);
}
}
};
/* 589. N-ary-Tree-Preorder-Traversal.cpp
//////////////////////////////////////////////////
Given 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).
Input: root = [1,null,3,2,4,null,5,6]
Output: [1,3,5,6,2,4]
https://leetcode.com/problems/n-ary-tree-preorder-traversal/
//////////////////////////////////////////////////
*/