二叉树的生成和遍历

来源:互联网 发布:淘宝mac上的软件能用么 编辑:程序博客网 时间:2024/05/29 07:32

  源文件

#include"define.h"int main(){bitree *root=create();printf("二叉树的先序遍历:\n");preorder(root);printf("\n");printf("中序遍历:\n");inorder(root);printf("\n");printf("后序遍历\n");postorder(root);printf("\n");return 0;}


头文件

#include<stdio.h>#include<malloc.h>#define MAXSIZE 1024typedef char datatype;typedef struct lnode{datatype data;struct lnode *lchild,*rchild;} bitree;//生成二叉树bitree *create(){bitree *root,*s,*Q[MAXSIZE];datatype x;unsigned int front=1,rear=0;scanf("%c",&x);while(x!='#'){if(x!='@'){s=(bitree *)malloc(sizeof(bitree));s->data=x;s->lchild=NULL;s->rchild=NULL;}rear++;Q[rear]=s;if(rear==1)root=s;else{if(rear%2)Q[front]->rchild=s;elseQ[front]->lchild=s;if(rear%2)front++;}scanf("%c",&x);}return root;}void preorder(bitree *root){bitree *t=root;if(t){printf("%c,",t->data);preorder(t->lchild);preorder(t->rchild);}}//中序遍历void inorder(bitree *root){bitree *t=root;if(t){inorder(t->lchild);printf("%c,",t->data);inorder(t->rchild);}}//后序遍历void postorder(bitree *root){bitree *t=root;if(t){postorder(t->lchild);postorder(t->rchild);printf("%c,",t->data);}}


 

原创粉丝点击