溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

二叉樹(shù)的創(chuàng)建和遍歷

發(fā)布時(shí)間:2020-08-08 14:37:08 來(lái)源:網(wǎng)絡(luò) 閱讀:390 作者:PlayWithYou 欄目:編程語(yǔ)言
#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問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI