-
Notifications
You must be signed in to change notification settings - Fork 0
/
429.n-ary-tree-level-order-traversal.cpp
79 lines (68 loc) · 1.42 KB
/
429.n-ary-tree-level-order-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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include <vector>
#include <queue>
using namespace std;
class Node {
public:
int val;
vector<Node*> children;
Node() {}
Node(int _val) {
val = _val;
}
Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
/*
* @lc app=leetcode id=429 lang=cpp
*
* [429] N-ary Tree Level Order Traversal
*/
// @lc code=start
/*
// 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<vector<int>> levelOrder(Node* root) {
if (!root) return{};
queue<Node*>q;
vector<vector<int>>result;
q.push(root);
while (!q.empty()) {
vector<int> tmp;
int size = q.size();
for (int i = 0; i < size; i++) {
for (auto j : q.front()->children) {
if (j != nullptr)q.push(j);
}
tmp.push_back(q.front()->val);
q.pop();
}
result.push_back(tmp);
}
return result;
}
};
// @lc code=end
int main() {
Solution s;
vector<Node*> v = { new Node(3), new Node(2), new Node(4) };
Node* n = new Node(1, v);
s.levelOrder(n);
return 0;
}