数据结构实验之二叉树二:遍历二叉树
Time Limit: 1000MS Memory Limit: 65536KB
Problem Description
已知二叉树的一个按先序遍历输入的字符序列,如abc,,de,g,,f,,, (其中,表示空结点)。请建立二叉树并按中序和后序的方式遍历该二叉树。
Input
连续输入多组数据,每组数据输入一个长度小于50个字符的字符串。
Output
每组输入数据对应输出2行:
第1行输出中序遍历序列;
第2行输出后序遍历序列。
Example Input
abc,,de,g,,f,,,
Example Output
cbegdfa
cgefdba
实现代码:
///先序建立二叉树 #include <stdio.h> #include <stdlib.h> struct node { char data; struct node *lt;/// 指向根的左子树 struct node *rt;///指向根的右子树 }; char st[100]; int flag; struct node *Creat()///建立二叉树,从字符数组st中读取数据 { if(st[++flag]==',') return NULL; struct node *root; root=(struct node *)malloc(sizeof(struct node)); root->data=st[flag]; root->lt=Creat();///建立左子树 root->rt=Creat();///建立右子树 return root; } ///先序遍历 void pre(struct node *root) { if(root) { printf("%c", root->data); pre(root->lt); pre(root->rt); } } ///中序遍历 void mid(struct node *root) { if(root) { mid(root->lt); printf("%c", root->data); mid(root->rt); } } ///后序遍历 void last(struct node *root) { if(root) { last(root->lt); last(root->rt); printf("%c", root->data); } } int main() { while(~scanf("%s", st)) { flag=-1; struct node *root; root=NULL; root=Creat(); pre(root);///先序遍历 mid(root);///中序遍历 printf("\n"); last(root);///后序遍历 printf("\n"); } return 0; }