二叉树的前序,中序,后续(非递归版本)

3 篇文章 0 订阅
3 篇文章 0 订阅

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


前言

二叉树的非递归版本的前序中序后序在面试中也经常考,必须熟练掌握!
下面将会讲如何非递归打印二叉树的前中后序。

一、前序

思路:递归改非递归一般都要用到数据结构栈,当前节点出栈的时候打印,并有右节点先加入右节点,
后加入左节点,因为前序根左右,而栈是逆序,所以先入有节点。

void Print(TreeNode* root)
{
    //前序
    stack<TreeNode*> s = stack<TreeNode*>();//创建栈
    s.push(root);//头结点入栈
     入栈顺序有右压右,有左压左
    while (!s.empty())
    {
        TreeNode* cur = s.top();
        s.pop();
        cout << to_string(cur->val)+"" ;
        if (cur->right)
        {
            s.push(cur->right);
        }
        if (cur->left)
        {
            s.push(cur->left);
        }

    }
}

二、后序

思路:与前序不同,后序我们需要两个栈进行调换,第一个栈得出的结果顺序是根右左,因为栈逆序,我们将s1栈中的数据放入s2就得到了左右根,后续操作和前序相似。

后序
    stack<TreeNode*> s1 = stack<TreeNode*>();
    stack<TreeNode*> s2 = stack<TreeNode*>();
    s1.push(root);
    while (!s1.empty())
    {
        TreeNode* cur = s1.top();
        s1.pop();
        s2.push(cur);
        if (cur->left)
        {
            s1.push(cur->left);
        }
        if (cur->right)
        {
            s1.push(cur->right);
        }
    }
    while (!s2.empty())
    {
        TreeNode* cur = s2.top();
        s2.pop();
        cout << cur->val << endl;
    }

三、中序

代码如下:

中序
    stack<TreeNode*> t = stack<TreeNode*>();
    TreeNode* cur = root;
    while (!t.empty() || cur!=nullptr)
    {

        if (cur!= nullptr)
        {
            t.push(cur);
            cur = cur->left;
        }
        else
        {
            cur = t.top();
            t.pop();
            cout << cur->val << endl;
            cur = cur->right;
        }
    }

总结

  • 32
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 25
    评论
评论 25
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

1无名之辈1

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值