-
Notifications
You must be signed in to change notification settings - Fork 344
/
Copy pathn-ary-tree-level-order-traversal.cpp
92 lines (76 loc) · 1.81 KB
/
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
80
81
82
83
84
85
86
87
88
89
90
91
92
#include <bits/stdc++.h>
using namespace std;
// Definition for a n-ary tree node.
class TreeNode {
public:
int val;
vector<TreeNode *> children;
TreeNode() {}
TreeNode(int val)
{
this->val = val;
}
TreeNode(int val, vector<TreeNode *> children)
{
this->val = val;
this->children = children;
}
};
vector<vector<int>> levelOrder(TreeNode *root,vector<vector<int>>&res) {
// vector<vector<int>> res;
if (root == NULL) {
return res;
}
queue<TreeNode *> q;
q.push(root);
while (!q.empty()) {
vector<int> temp;
int n = q.size();
for (int i = 0; i < n; i++) {
TreeNode *cur = q.front();
q.pop();
for (int i = 0; i < cur->children.size(); i++) {
q.push(cur->children[i]);
}
temp.push_back(cur->val);
}
res.push_back(temp);
}
return res;
}
//Displaying result
void printResult(vector<vector<int>> result) {
cout<<"[";
for(int i=0;i<result.size();i++) {
for(int j=0;j<result[i].size();j++) {
if(j==0) {
cout<<"[";
}
cout<<result[i][j];
if(j!=result[i].size()-1) {
cout<<",";
}
}
cout<<"]";
if(i!=result.size()-1) {
cout<<",";
}
}
cout<<"]"<<endl;
}
int main() {
/*
Tree Looks like this:-
1
/ | \
3 2 4
/ \
5 6
*/
TreeNode *child1=new TreeNode(3,{new TreeNode(5),new TreeNode(6)});
TreeNode *root=new TreeNode(1,{child1,new TreeNode(2),new TreeNode(4)});
vector<vector<int>> result;
levelOrder(root,result);
printResult(vector<vector<int>> result);
return 0;
}