关于二叉树的三种遍历的迭代写法

前几天在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;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值