温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

二叉树的创建和遍历

发布时间:2020-08-08 14:37:08 来源:网络 阅读:386 作者:PlayWithYou 栏目:编程语言
#include<stdio.h>
#include<stdlib.h>
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;
}


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI