文章目录
1. 题目2. 解题2.1 递归2.2 循环1. 题目
2. 解题
2.1 递归
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 循环
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;}};