题目描述:
递归法:跟二叉树的前序遍历类似。
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children;
Node() {}
Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public:
vector<int> res;
vector<int> preorder(Node* root) {
if(root==NULL)
return res;
res.push_back(root->val);
for(Node* child:root->children){
preorder(child);
}
return res;
}
};
递推算法:采用stack来完成
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children;
Node() {}
Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public:
vector<int> preorder(Node* root) {
if(root==NULL) return {};
stack<Node*> stk;
vector<int> res;
stk.push(root);
while(!stk.empty()) {
Node* temp=stk.top();
stk.pop();
for(int i=temp->children.size()-1;i>=0;i--) stk.push(temp->children[i]);//倒放子节点
res.push_back(temp->val);
}
return res;
}
};
还有一种递推形式的先序遍历,未完待续…