1. 题目
2. 解题
2.1 递归
代码语言:javascript
复制class Solution {
public:
vector<int> preorder(Node* root) {
vector<int> ans;
preRec(root,ans);
return ans;
}
void preRec(Node* root, vector<int> &ans)
{
if(root == NULL)
return;
ans.push_back(root->val);
for(int i = 0; i < root->children.size(); i)
preRec(root->children[i], ans);
}
};
2.2 循环
代码语言:javascript
复制class Solution {
public:
vector<int> preorder(Node* root) {
if(root == NULL)
return {};
vector<int> ans;
stack<Node*> stk;
Node *tp;
int i;
stk.push(root);
while(!stk.empty())
{
tp = stk.top();
ans.push_back(tp->val);
i = tp->children.size();
stk.pop();
while(i)
{
stk.push(tp->children[--i]);
}
}
return ans;
}
};