您的位置:首页 > 理论基础 > 数据结构算法

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

2016-10-30 21:55 399 查看
数据结构实验之二叉树二:遍历二叉树

#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 mid(struct node *root)//中序遍历
{
if(root)
{
mid(root->lchild);
printf("%c",root->data);
mid(root->rchild);
}
}
void after(struct node *root)  //后序遍历
{
if(root)
{
after(root->lchild);
after(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();
mid(root);
printf("\n");
after(root);
printf("\n");
}return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  二叉树