二叉树的层序遍历

#include<iostream>
#include<stack>
using namespace std;

//二叉树数据结构
typedef struct TreeNode
{
    char data;
    struct TreeNode *Leftchild;
    struct TreeNode *Rightchild;
    TreeNode(char c)
    {
        data=c;
        Leftchild=NULL;
        Rightchild=NULL;
    }
} TreeNode,*Tree;

//创建二叉树
void CreateTree(Tree &p)
{
    char c;
    cin>>c;
    if(c=='#') p=NULL;
    else
    {
        p=new TreeNode(c);
        cout<<"请输入"<<p->data<<"的左子树: ";
        CreateTree(p->Leftchild);
        cout<<"请输入"<<p->data<<"的右子树: ";
        CreateTree(p->Rightchild);
    }
}

//先序遍历
void PreOrder(Tree &T)
{
    stack<Tree> S;
    Tree p=T;
    while(p||!S.empty())
    {
        if(p)
        {
            cout<<p->data<<" ";
            S.push(p);
            p=p->Leftchild;
        }
        else
        {
            p=S.top()->Rightchild;
            S.pop();
        }
    }
}

//中序遍历
void InOrder(Tree &T)
{
    stack<Tree> S;
    Tree p=T;
    while(p||!S.empty())
    {
        if(p)
        {
            S.push(p);
            p=p->Leftchild;
        }
        else
        {
            p=S.top();
            cout<<p->data<<" ";
            p=p->Rightchild;
            S.pop();
        }
    }
}

//后序遍历
void PostOrder(Tree &T)
{
    Tree p=T;
    stack<Tree> S;
    stack<char> SS;
    while(p||!S.empty())
    {
        if(p)
        {
            SS.push(p->data);
            S.push(p);
            p=p->Rightchild;
        }
        else
        {
            p=S.top()->Leftchild;
            S.pop();
        }
    }
    while(!SS.empty())
    {
        cout<<SS.top()<<" ";
        SS.pop();
    }
}

int main()
{
    Tree p=NULL;
    cout<<"创建二叉树,请输入根节点(#表示节点为空): ";
    CreateTree(p);
    cout<<"先序遍历: ";
    PreOrder(p);
    cout<<endl;
    cout<<"中序遍历: ";
    InOrder(p);
    cout<<endl;
    cout<<"后序遍历: ";
    PostOrder(p);
    return 0;
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值