775. N-ary Tree Preorder Traversal
Difficulty: Easy
Topics: Tree
Similar Questions:
Problem:
Given an n-ary tree, return the preorder traversal of its nodes' values.
For example, given a 3-ary
tree:
Return its preorder traversal as: [1,3,5,6,2,4]
.
Note:
Recursive solution is trivial, could you do it iteratively?
Solutions:
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children;
Node() {}
Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public:
vector<int> preorder(Node* root) {
vector<int> ret;
helper(root, ret);
return ret;
}
private:
void helper(Node* root, vector<int>& ret) {
if (root == nullptr) return;
ret.push_back(root->val);
for (auto& child : root->children) {
helper(child, ret);
}
}
};