think:
1 通过中序遍历和后序遍历还原二叉树
2 二叉树的层序遍历(队列思想)
sdut原题链接
求二叉树的层次遍历
Time Limit: 1000MS Memory Limit: 65536KB
Problem Description
已知一颗二叉树的前序遍历和中序遍历,求二叉树的层次遍历。
Input
输入数据有多组,输入T,代表有T组测试数据。每组数据有两个长度小于50的字符串,第一个字符串为前序遍历,第二个为中序遍历。
Output
每组输出这颗二叉树的层次遍历。
Example Input
2
abc
bac
abdec
dbeac
Example Output
abc
abcde
Hint
Author
fmh
以下为accepted代码
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct node
{
char date;
struct node *left;
struct node *right;
}BinTree;
BinTree *root, *link[54];
char st1[54], st2[54];
BinTree * get_build(int len, char *st1, char *st2)//建立二叉树
{
if(len == 0)
return NULL;
int i;
BinTree *root;
root = (BinTree *)malloc(sizeof(BinTree));
root->date = st1[0];//寻找根节点,新的根节点为前序遍历st1的第一个
for(i = 0; i < len; i++)//寻找新的根节点在中序遍历st2中的位置
{
if(st2[i] == root->date)
break;
}
root->left = get_build(i, st1+1, st2);//(左子树的长度,左子树在前序遍历中的开始位置,左子树在中序遍历中的开始位置)
root->right = get_build(len-i-1, st1+i+1, st2+i+1);//(右子树的长度,右子树在前序遍历中的位置,右子树在中序遍历中的位置)
return root;
}
void ans(BinTree *root)//二叉树的层序遍历
{
if(root)///判断root是否为NULL
{
int i = 0, j = 0;
link[j++] = root;
while(i < j)
{
if(link[i])
{
link[j++] = link[i]->left;//入队
link[j++] = link[i]->right;//入队
printf("%c", link[i]->date);//层序遍历
}
i++;//出队
}
}
}
int main()
{
int T, len;
scanf("%d", &T);
while(T--)
{
scanf("%s %s", st1, st2);
len = strlen(st1);
root = get_build(len, st1, st2);//调用建立二叉树函数
ans(root);//调用二叉树的层序遍历函数
printf("\n");
}
return 0;
}
/***************************************************
User name: jk160630
Result: Accepted
Take time: 0ms
Take Memory: 112KB
Submit time: 2017-02-08 08:40:58
****************************************************/