给定一个 N 叉树,返回其节点值的前序遍历。
例如,给定一个 3叉树
:
返回其前序遍历: [1,3,5,6,2,4]
。
说明: 递归法很简单,你可以使用迭代法完成此题吗?
解法一:递归
class Solution {
public:
vector<int> res;
vector<int> preorder(Node* root) {
pre_Traversal(root);
return res;
}
void pre_Traversal(Node* root) {
if(root) {
res.push_back(root->val);
for(int i = 0; i < root->children.size(); i++) {
pre_Traversal(root->children[i]);
}
}
}
};
解法二:手动维护一个栈,参照二叉树的手动维护栈的框架
class Solution {
public:
vector<int> preorder(Node* root) {
vector<int> res;
stack<Node*> call;
if(root) call.push(root);
while(!call.empty()) {
Node* tmp = call.top();
call.pop();
if(tmp != nullptr) {
for(int i = tmp->children.size() - 1; i >= 0; i--) {
call.push(tmp->children[i]);
}
call.push(tmp);
call.push(nullptr);
}
else {
res.push_back(call.top()->val);
call.pop();
}
}
return res;
}
};