题目描述:
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]
.
class Solution {
public:
vector<int> preorder(Node* root) {
vector<int> result;
if(root==NULL) return result;
stack<Node*> s;
s.push(root);
while(!s.empty())
{
Node* cur=s.top();
s.pop();
result.push_back(cur->val); // 先虚遍历直接去栈顶访问
// 倒着将所有子节点压栈,这样保证每次都是访问到第一个子节点
for(int i=cur->children.size()-1;i>=0;i--)
s.push(cur->children[i]);
}
return result;
}
};