二叉树

来源:互联网 发布:法语发音规则总结知乎 编辑:程序博客网 时间:2024/04/20 05:40
//#include <stdio.h>
#include <iostream.h>
#include 
<malloc.h>

int i;

struct bt{
    
char elem;
    
struct bt *l;
    
struct bt *r;
}
;

//先序生成二叉树
struct bt * Creat(struct bt *t,char *elem){
    
//if(i>j)
    
//    return NULL;
    if(elem[i]=='#'){
        t
=NULL;
        i
++;
    }
else{        
        t
=(struct bt *)malloc(sizeof(struct bt));
        t
->elem=elem[i];
        i
++;
        t
->l=Creat(t->l,elem);
        t
->r=Creat(t->r,elem);
    }

    
return t;
}


//先序遍历输出二叉树
void TPreOut(struct bt *t){
    
if(t==NULL){
        cout
<<"#";
        
return;
    }
else{
        cout
<<t->elem;
        TPreOut(t
->l);
        TPreOut(t
->r);
    }

}


//中序遍历输出二叉树
void TMiOut(struct bt *t){
    
if(t==NULL){
        cout
<<"#";
        
return;
    }
else{
        TMiOut(t
->l);
        cout
<<t->elem;
        TMiOut(t
->r);
    }

}


//后序遍历输出二叉树
void TBaOut(struct bt *t){
    
if(t==NULL){
        cout
<<"#";
        
return;
    }
else{
        TBaOut(t
->l);
        TBaOut(t
->r);
        cout
<<t->elem;
    }

}



void main(){
    
struct bt *b;
    
struct bt *parent;
    
char elem[100]; 
    cout
<<"先序生成二叉树输入: ";
    cin
>>elem;
    i
=0;
    b
=Creat(b,elem);
    parent
=b;
    cout
<<"先序输出二叉树 ";
    TPreOut(parent);
    cout
<<" 中序输出二叉树 ";
    TMiOut(parent);
    cout
<<" 后序输出二叉树 ";
    TBaOut(parent);
}
 
原创粉丝点击