题目
法一、递归
1 class Solution { 2 public: 3 vector<int>ans; 4 void dfs(Node* root){ 5 if(root!=NULL){ 6 ans.push_back(root->val); 7 for(int i = 0;i < root->children.size();i++) 8 preorder(root->children[i]); 9 } 10 } 11 vector<int> preorder(Node* root) { 12 dfs(root); 13 return ans; 14 } 15 };
法二,用栈迭代
1 class Solution { 2 public: 3 vector<int> preorder(Node* root) { 4 vector<int>ans; 5 stack<Node*>v; 6 if(root==NULL) return ans; 7 v.push(root); 8 while(!v.empty()){ 9 Node *node = v.top();v.pop(); 10 if(node) ans.push_back(node->val); 11 else continue; 12 13 for(int i = node->children.size()-1;i >= 0;i--){ 14 v.push(node->children[i]); 15 } 16 } 17 return ans; 18 } 19 };