Creation and traversal of binary tree

#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));
    }
}
// preorder traversal
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");
}
// in-order traversal
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");
}
// post-order traversal
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");
}
intmain()
{
    BTree *t=NULL;
    createTree(&t);
    printf("start treverse\n");
    preorderTraverse(t);
    printf("\n");
    inorderTraverse(t);
    printf("\n");
    postorderTraverse(t);
    printf("\n");
    return 0;
}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324812464&siteId=291194637