1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-09 15:59:06 +01:00
LeetCode/cpp/n-ary-tree-level-order-traversal.cpp
Matej Focko b229608723
cpp(chore): add clang-format style and format
Signed-off-by: Matej Focko <me@mfocko.xyz>
2024-01-03 12:06:54 +01:00

45 lines
843 B
C++

/*
// 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;
}
};