LeetCode-589. N-ary Tree Preorder Traversal
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?
题解:
class Solution {
public:
static void preOrder(Node* root, vector<int> &ans) {
if (root != NULL) {
ans.push_back(root->val);
for (int i = 0; i < root->children.size(); i++) {
preOrder(root->children[i], ans);
}
}
}
vector<int> preorder(Node* root) {
vector<int> ans;
preOrder(root, ans);
return ans;
}
};