我的二叉树,从利用前序遍历建立一颗二叉树开始。此题为利用前序遍历建立一颗二叉树并用中序以及后序遍历输出。
数据结构实验之二叉树二:遍历二叉树
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>
#include<string.h>
typedef struct node
{
char data;
struct node *lchild; //左孩子
struct node *rchild; //右孩子
}Tree;
char str[52]; //先序遍历的字符串
int q;
Tree *creat(); //利用前序遍历建立一颗二叉树
void midsort(Tree *root); //中序遍历
void lastsort(Tree *root); //后序遍历
int main()
{
Tree *root; //建立树根结点
while(~scanf("%s", str)) //输入先序遍历的字符串
{
getchar();
q = -1;
root = creat(); //利用先序遍历建立一颗二叉树
midsort(root); //中序遍历输出
printf("\n");
lastsort(root); //后序遍历输出
printf("\n");
}
return 0;
}
Tree *creat() //利用先序遍历建立一颗二叉树
{
Tree *root; //建立树根
if(str[++q] == ',') //如果这一个结点的data是‘,’此结点为空
{
root = NULL;
}
else //如果不为空
{
root = (Tree *)malloc(sizeof(Tree)); //为此结点开下空间
root->data = str[q]; //把data域填起来
root->lchild = creat(); //再去建它的左孩子看它是不是空
root->rchild = creat(); //再去建它的右孩子看它是不是空
}
return root; //最后返回大的根结点
}
void midsort(Tree *root) //中序遍历输出
{
if(root) //如果是空就返回上一层了
{
midsort(root->lchild); //先遍历左孩子
printf("%c", root->data); //再遍历根结点
midsort(root->rchild); //最后遍历右孩子
}
}
void lastsort(Tree *root) //后序遍历输出
{
if(root) //如果是空就返回上一层了
{
lastsort(root->lchild); //先遍历左孩子
lastsort(root->rchild); //再遍历右孩子
printf("%c", root->data); //最后遍历根结点
}
}