数据结构 二叉树的建立 与各种遍历

#include <iostream>
#include <string.h>
using namespace std;
class tree
{
    public:
    char c;
    tree* rchild,*lchild;
};
char c;
int main()
{
    void build(tree *&p);
    void Preorder(tree *p);
    void Inorder1(tree *p);
    void Inorder2(tree *p);
    void Inorder3(tree *p);
    void Postorder(tree *p);
    int i,j,n,m,s,t;
    tree *head;
    build(head);
    cout<<"先序递归遍历:"<<endl;
    Preorder(head);
    cout<<endl;
    cout<<"中序递归遍历遍历:"<<endl;
    Inorder1(head);
    cout<<endl;
    cout<<"中序非递归遍历:"<<endl;
    Inorder2(head);
    cout<<endl;
    cout<<"中序非递归遍历:"<<endl;
    Inorder3(head);
    cout<<endl;
    cout<<"后续遍历:"<<endl;
    Postorder(head);
    cout<<endl;
    return 0;
}
void build(tree *&p)
{
    cin>>c;
    if(c=='$')
    {
        p=NULL;
    }else
    {
        p=new(tree);
        p->c=c;
        build(p->lchild);
        build(p->rchild);
    }
}
void Preorder(tree *p)
{
    if(p)
    {
        cout<<p->c;
        Preorder(p->lchild);
        Preorder(p->rchild);
    }
}
void Inorder1(tree *p)
{
    if(p)
    {
        Inorder1(p->lchild);
        cout<<p->c;
        Inorder1(p->rchild);
    }
}
void Inorder2(tree *p)
{
    int top=0;
    tree* statck[10000];
    statck[top++]=p;
    while(top>0)
    {
        while((p=statck[top-1])&&p)
        {
            p=p->lchild;
            statck[top++]=p;
        }
        top-=1;
        if(top>0)
        {
            p=statck[--top];
            cout<<p->c;
            statck[top++]=p->rchild;
        }
    }
}
void Inorder3(tree *p)
{
    int top=0;
    tree* statck[100000];
    while(p||top>0)
    {
        if(p)
        {
            statck[top++]=p;
            p=p->lchild;
        }else
        {
            p=statck[--top];
            cout<<p->c;
            p=p->rchild;
        }
    }
}
void Postorder(tree *p)
{
    if(p)
    {
        Postorder(p->lchild);
        Postorder(p->rchild);
        cout<<p->c;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值