前几天在leetcode上看到一位大佬写的二叉树的迭代写法,博主觉得非常好记实用便记录下来。
struct TreeNode{
TreeNode *right,*left;
int val;
};
先序写法(入栈顺序为右左中)
vector<int> preorder(TreeNode * root){
vector<int>res;
stack<TreeNode*> st
if(root!=nullptr) st.push(root);
while(!st.empty()){
TreeNode *t=st.top();
st.pop();
if(t!=nullptr){
if(t->right)st.push(t->right);
if(t->left)st.push(t->left);
st.push(t);
st.push(nullptr);//用来标记结点是否访问
}
else{
res.push_back(st.top()->val);
st.pop();}
}
return res;
}
中序写法:入栈顺序右中左
vector<int> preorder(TreeNode * root){
vector<int>res;
stack<TreeNode*> st
if(root!=nullptr) st.push(root);
while(!st.empty()){
TreeNode *t=st.top();
st.pop();
if(t!=nullptr){
if(t->right)st.push(t->right);
st.push(t);
st.push(nullptr);//用来标记结点是否访问
if(t->left)st.push(t->left);
}
else{
res.push_back(st.top()->val);
st.pop();}
}
return res;
}
后序写法:入栈顺序中右左
vector<int> preorder(TreeNode * root){
vector<int>res;
stack<TreeNode*> st
if(root!=nullptr) st.push(root);
while(!st.empty()){
TreeNode *t=st.top();
st.pop();
if(t!=nullptr){
st.push(t);
st.push(nullptr);//用来标记结点是否访问
if(t->right)st.push(t->right);
if(t->left)st.push(t->left);
}
else{
res.push_back(st.top()->val);
st.pop();}
}
return res;
}
利用这个写法只需改变入栈顺序就能轻松写出二叉树三种遍历的迭代表达
下给出一个leetcode的应用实例:题号589(简单题)
题目描述:
结构体描述:
class Node {
public:
int val;
vector<Node*> children;
Node() {}
Node(int _val) {
val = _val;
}
Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
模仿上述写法最终AC的迭代写法:
vector<int> preorder(Node* root) {
vector<int>res;
stack<Node *>st;
if(root!=nullptr)
st.push(root);
while(!st.empty()){
Node *t=st.top();
st.pop();
if(t!=nullptr){
if(t->children.size()!=0){
for(int i=t->children.size()-1;i>=0;i--)
st.push(t->children[i]);
}
st.push(t);
st.push(nullptr);
}
else{
res.push_back(st.top()->val);
st.pop();
}
}
return res;
}