给定一个 N 叉树,返回其节点值的后序遍历。
例如,给定一个 3叉树
:
返回其后序遍历: [5,6,3,2,4,1]
.
说明: 递归法很简单,你可以使用迭代法完成此题吗?
解法一:递归
class Solution {
public:
//存放结果
vector<int> res;
vector<int> postorder(Node* root) {
post_Traversal(root);
return res;
}
void post_Traversal(Node* root) {
//模仿二叉树的后序遍历,注意children是个vector。
if(root) {
for(int i = 0; i < root->children.size(); i++) {
post_Traversal(root->children[i]);
}
res.push_back(root->val);
}
}
};
解法二:手动维护一个栈,框架参照二叉树手动维护栈的框架
class Solution {
public:
vector<int> postorder(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) {
call.push(tmp);
call.push(nullptr);
for(int i = tmp->children.size() -1; i >= 0; i--) {
call.push(tmp->children[i]);
}
}
else {
res.push_back(call.top()->val);
call.pop();
}
}
return res;
}
};