数据结构实验之二叉树二:遍历二叉树
Time Limit: 1000 ms Memory Limit: 65536 KiB
Problem Description
已知二叉树的一个按先序遍历输入的字符序列,如abc,,de,g,,f,,, (其中,表示空结点)。请建立二叉树并按中序和后序的方式遍历该二叉树。
Input
连续输入多组数据,每组数据输入一个长度小于50个字符的字符串。
Output
每组输入数据对应输出2行:
第1行输出中序遍历序列;
第2行输出后序遍历序列。
Sample Input
abc,,de,g,,f,,,
Sample Output
cbegdfa
cgefdba
Hint
Source
xam
这道题就是考察中序和后序遍历二叉树的规则,如果是中序遍历的话,先遍历左子树,然后输出根节点,之后遍历右子树。而后序遍历则是先遍历左子树,然后是右子树,最后是根节点。其实前中后遍历的方法就是根据根节点遍历的先后顺序来决定的。此外,本题还考察了二叉树的建立,二叉树的建立实际上是充分利用了递归的思想,从根节点逐层递归到叶子结点即最深层结点。本人比较喜欢用链表进行二叉树的建立。因为不容易丢失数据。详情见AC代码。
AC代码:
#include<bits/stdc++.h>
using namespace std;
char a[100];//用a数组来作为中继数组存放数据
int x;
struct node//树节点的建立
{
int data;
struct node*lchild,*rchild;//定义左孩子和右孩子
};
struct node*creat()//二叉树的建立
{
struct node*root;
char c;
c=a[x++];
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))
{
x=0;
root=(struct node*)malloc(sizeof(struct node));
root=creat();
mid(root);
printf("\n");
after(root);
printf("\n");
}
return 0;
}
来源:https://blog.csdn.net/weixin_44015865/article/details/102761327