我们专注攀枝花网站设计 攀枝花网站制作 攀枝花网站建设
成都网站建设公司服务热线:400-028-6601

网站建设知识

十年网站开发经验 + 多家企业客户 + 靠谱的建站团队

量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决

二叉树的创建和遍历

#include
#include
typedef struct Tree{
    char data;
    struct Tree *lchild;
    struct Tree *rchild;
}BTree;
void createTree(BTree **t)
{
    char c;
    scanf("%c",&c);
    if(c==' ')
      *t=NULL;
    else if(c!='\0'&&c!='\x0a'){
        if(!(*t=(BTree *)malloc(sizeof(BTree))))
          exit(0);
        (*t)->data=c;
        createTree(&((*t)->lchild));
        createTree(&((*t)->rchild));
    }
}
//先序遍历
void preorderTraverse(BTree *t)
{
    if(t!=NULL){
        printf("%c",t->data);
        if(t->lchild!=NULL)
          preorderTraverse(t->lchild);
        else
          printf("*");
        if(t->rchild!=NULL)
          preorderTraverse(t->rchild);
        else
          printf("*");
    }else
      printf("Thia tree is null\n");
}
//中序遍历
void inorderTraverse(BTree *t)
{
    if(t!=NULL){
        if(t->lchild!=NULL)
        inorderTraverse(t->lchild);
        else
          printf("*");
        printf("%c",t->data);
        if(t->rchild!=NULL)
          inorderTraverse(t->rchild);
        else
          printf("*");
    }else
      printf("Thia tree is null\n");
}
//后序遍历
void postorderTraverse(BTree *t)
{
    if(t!=NULL){
        if(t->lchild!=NULL)
          postorderTraverse(t->lchild);
        else
          printf("*");
        if(t->rchild!=NULL)
          postorderTraverse(t->rchild);
        else
          printf("*");
        printf("%c",t->data);
    }else
      printf("Thia tree is null\n");
}
int main()
{
    BTree *t=NULL;
    createTree(&t);
    printf("start treverse\n");
    preorderTraverse(t);
    printf("\n");
    inorderTraverse(t);
    printf("\n");
    postorderTraverse(t);
    printf("\n");
    return 0;
}

分享名称:二叉树的创建和遍历
标题网址:http://shouzuofang.com/article/gjjpoi.html

其他资讯