C++树的建立和遍历

#include<iostream.h>
typedef char TElemtype;
typedef struct Btree
{
    TElemtype data;
    struct Btree *Lchild,*Rchild;
}BTnode,*btree;

void create_btree(btree &root) 
{
    int i,j;
    btree s,p[100];  
    cin>>i;
    while(i!=0)      
    {
        s=new BTnode; 
        cin>>s->data;
        s->Lchild=s->Rchild=NULL;
        p[i]=s;                    
        if(i==1)        
            root=s;
        else
        {
            j=i/2;        
            if(i%2==0)
                p[j]->Lchild=s;
            else
                p[j]->Rchild=s;
        }
        cin>>i;       
    }
}

void create_btree2(btree &root,char str[])   
                
{
    char ch;
    static int i=0; 
    ch=str[i++];
    if(ch=='.')
    {
        root=NULL;
    }
    else
    {
        root=new BTnode;
        root->data=ch;
        create_btree2(root->Lchild,str);
        create_btree2(root->Rchild,str);
    }
}

void preorder(btree root)     
{
    if(root)
    {
        cout<<root->data;
        preorder(root->Lchild);
        preorder(root->Rchild);

    }
}

void inorder(btree root)    
{
    if(root)
    {
        inorder(root->Lchild);
        cout<<root->data;

        inorder(root->Lchild);
        
    }

}

void postorder(btree root)        
{
    if(root)
    {
        postorder(root->Lchild);
        postorder(root->Lchild);
        cout<<root->data;
    }
}
void main()
{
    btree root;
    //create_btree(root);
    char str[30];
    cin>>str;
    create_btree2(root,str);
    preorder(root);
    
    
}

 

posted on 2018-05-03 13:53  肀肀  阅读(3127)  评论(0编辑  收藏  举报

导航