590. N 叉树的后序遍历
1.递归
很easy
/*
// 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* rt) {
vector<int>ans;
function<void(Node*rt)> dfs = [&](Node*rt){
if(rt==nullptr) return;
for(auto son:rt->children){
dfs(son);
}
ans.push_back(rt->val);
};
dfs(rt);
return ans;
}
};
2.迭代
用栈,然后反后序,也就是右左根顺序,同时用一个标记数组维护该结点及子树是否都遍历过。
class Solution {
public:
vector<int> postorder(Node* rt) {
vector<int> res;
if (rt == nullptr) {
return res;
}
stack<Node*>st;
unordered_map<Node*,bool>vis;
st.push(rt);
vector<int>b;
while(!st.empty()){
Node* u = st.top();
if((int)u->children.size()==0 || vis[u]){
b.push_back(u->val);
st.pop();
continue;
}
for(auto it = u->children.rbegin();it!=u->children.rend();it++){
st.push(*it);
}
vis[u] = 1;
}
return b;
}
};