题目描述:
给定一个 N 叉树,返回其节点值的后序遍历。
例如,给定一个 3叉树 :
返回其后序遍历: [5,6,3,2,4,1].
说明: 递归法很简单,你可以使用迭代法完成此题吗?
方法1:递归
主要思路:
(1)直接使用二叉树的后序遍历思路,将结点的每个子节点从左到右递归调用一遍,并在最后将结点值压入结果中;
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children;
Node() {}
Node(int _val) {
val = _val;
}
Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public:
void helper(Node* root,vector<int>& res){
if(root==NULL){
return;
}
for(int i=0;i<root->children.size();++i){
helper(root->children[i],res);//遍历当前结点的所有子节点
}
res.push_back(root->val);
}
vector<int> postorder(Node* root) {
vector<int> res;
helper(root,res);
return res;
}
};
方法2:迭代,使用先序遍历再反序
主要思路:
(1)还是使用前序遍历的思路,只不过压入的顺序又从右向左变成从左到右,并对最终的结果实现反序;
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children;
Node() {}
Node(int _val) {
val = _val;
}
Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public:
vector<int> postorder(Node* root) {
if(root==NULL){
return {};
}
stack<Node*> st;
vector<int> res;
st.push(root);
Node* cur_node=NULL;
while(!st.empty()){
cur_node=st.top();
st.pop();
res.push_back(cur_node->val);
for(int i=0;i<cur_node->children.size();++i){//注意压入的顺序
st.push(cur_node->children[i]);
}
}
reverse(res.begin(),res.end());//最后对结果进行反序
return res;
}
};