problems: add n-ary tree level-order traversal
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
6c3cfcd876
commit
7c3f9ba87e
1 changed files with 47 additions and 0 deletions
47
problems/n-ary-tree-level-order-traversal.cpp
Normal file
47
problems/n-ary-tree-level-order-traversal.cpp
Normal file
|
@ -0,0 +1,47 @@
|
||||||
|
/*
|
||||||
|
// 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 {
|
||||||
|
void levelOrder(vector<vector<int>>& traversal, Node* root, int level)
|
||||||
|
{
|
||||||
|
if (root == nullptr) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (level >= traversal.size()) {
|
||||||
|
traversal.push_back({});
|
||||||
|
}
|
||||||
|
traversal[level].push_back(root->val);
|
||||||
|
|
||||||
|
for (auto child : root->children) {
|
||||||
|
levelOrder(traversal, child, level + 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public:
|
||||||
|
vector<vector<int>> levelOrder(Node* root)
|
||||||
|
{
|
||||||
|
vector<vector<int>> result;
|
||||||
|
levelOrder(result, root, 0);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
};
|
Loading…
Reference in a new issue