3341 数据结构实验之二叉树二:遍历二叉树

来源:互联网 发布:c语言调用大漠插件 编辑:程序博客网 时间:2024/06/05 10:14

数据结构实验之二叉树二:遍历二叉树

#include<stdio.h>#include<string.h>#include<stdlib.h>char a[100];int l1;struct node //二叉树的定义{int data;struct node *lchild,*rchild;};struct node *creat()  //建立二叉树{struct node  *root;char c;c=a[l1++];if(c==',')    return NULL;else{    root=(struct node *)malloc(sizeof(struct node));root->data=c;root->lchild=creat();root->rchild=creat();}return root;}void zhong(struct node *root)//中序遍历{if(root){zhong(root->lchild);printf("%c",root->data);zhong(root->rchild);}}void hou(struct node *root)  //后序遍历{if(root){hou(root->lchild);hou(root->rchild);printf("%c",root->data);}}int main(){struct node *root;while(scanf("%s",a)!=EOF){    l1=0;    root=(struct node *)malloc(sizeof(struct node));root=creat();zhong(root);printf("\n");hou(root);printf("\n");}return 0;}
0 0
原创粉丝点击