码迷,mamicode.com
首页 > 其他好文 > 详细

二叉树的创建和遍历

时间:2018-04-24 21:46:00      阅读:93      评论:0      收藏:0      [点我收藏+]

标签:二叉树   遍历   

#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; }


二叉树的创建和遍历

标签:二叉树   遍历   

原文地址:http://blog.51cto.com/9409270/2107425

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!