学习一下N叉树的后序遍历。
题目链接:链接
/*
// 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 travel(Node* cur, vector<int> & vec){
if(cur == nullptr) return;
// 后序遍历是左-右- 中,所以最后再读取。
for(Node * child: cur->children){
// children是从左到右依次读取。因此是左右中。
// n叉树不存在中序遍历。
travel(child, vec);
}
vec.push_back(cur->val);
}
vector<int> postorder(Node* root) {
vector<int> result;
travel(root, result);
return result;
}
*/
//统一迭代法实现
vector<int> postorder(Node* root) {
vector<int> result;
stack<Node*> st;
if(root != nullptr) st.push(root);
while(!st.empty()){
// 读取节点
Node * cur_node = st.top();
if(cur_node != nullptr) {
st.pop(); // 访问过的节点先弹出,以免后面重复操作
// 后序遍历是左-右-中。因此入栈顺序是:中-右-左
st.push(cur_node);
st.push(nullptr); // 空指针作为标记
// 子节点入栈
for(auto i=cur_node->children.crbegin(); i!= cur_node->children.crend(); i++){
st.push(*i);
}
}
else{//当遇到null标记
st.pop(); // 弹出标记
cur_node = st.top();
st.pop();
result.push_back(cur_node->val);
}
}
return result;
}
};