题目:
算法思想:递归开全局变量vector存储,调用自己就行了。迭代需要用栈,从右到左进栈,这样出栈就是先序遍历。
代码:
//递归版本
vector<int> result;
vector<int> preorder(Node* root) {
if(root == NULL)
return result;
else
result.push_back(root->val);
for(int i = 0;i < root->children.size();i++)
{
if(root->children[i] != NULL)
preorder(root->children[i]);
}
return result;
}
//迭代
vector<int> preorder(Node* root) {
vector<int> result;
stack<Node*> tmp;
if(root == NULL)
return result;
tmp.push(root);
while(!tmp.empty())
{
Node* a = tmp.top();
tmp.pop();
result.push_back(a->val);
for(int i = a->children.size()-1;i >= 0;i--)
tmp.push(a->children[i]);
}
return result;
}