mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-10 00:09:06 +01:00
problems: add n-ary tree preorder traversal
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
7c3f9ba87e
commit
b59f949d8f
1 changed files with 43 additions and 0 deletions
43
problems/n-ary-tree-preorder-traversal.cpp
Normal file
43
problems/n-ary-tree-preorder-traversal.cpp
Normal file
|
@ -0,0 +1,43 @@
|
||||||
|
/*
|
||||||
|
// 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 preorder(vector<int>& traversal, Node* root)
|
||||||
|
{
|
||||||
|
if (root == nullptr) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
traversal.push_back(root->val);
|
||||||
|
for (auto child : root->children) {
|
||||||
|
preorder(traversal, child);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public:
|
||||||
|
vector<int> preorder(Node* root)
|
||||||
|
{
|
||||||
|
vector<int> result;
|
||||||
|
preorder(result, root);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
};
|
Loading…
Reference in a new issue