链表题解链接见下
sdut oj 求二叉树的层次遍历(先序中序->二叉树 层序输出)(链表).
数组模拟见下文
Description
已知一颗二叉树的前序遍历和中序遍历,求二叉树的层次遍历。
Input
输入数据有多组,输入T,代表有T组测试数据。每组数据有两个长度小于50的字符串,第一个字符串为前序遍历,第二个为中序遍历。
Output
每组输出这颗二叉树的层次遍历。
Sample
Input
2
abc
bac
abdec
dbeac
Output
abc
abcde
C++
/*
time : 2021年7月26日17:22:29
result : accept
author : kirie
tips : null
*/
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#define rep(i,a,n) for(int i=a;i<n;i++)
using namespace std;
const int N=1e4+7;
struct tree {
char data;///字符型数据
int lc, rc;///左孩子,右孩子
}a[N];///节点的结构
int cnt;///树的序号,当有元素要存到里面时才自增1
int create(char pre[], char mid[], int len){
if(len <= 0)
return -1;
int id = cnt ++;
a[id].data = pre[0];
int i;
for(i = 0;i < len; i++){
if(mid[i] == pre[0])
break;
}
a[id].lc = create(pre+1, mid, i);
a[id].rc = create(pre+1+i, mid+1+i, len-i-1);
return id;
}
void seq_show(int root){//Sequence 层序
if(root == -1) return ;
queue<int> q;
q.push(root);
while(!q.empty()){
int id = q.front();
q.pop();
printf("%c",a[id].data);
if(a[id].lc != -1)
q.push(a[id].lc);
if(a[id].rc != -1)
q.push(a[id].rc);
}
}
int main()
{
int t;
cin>>t;
while(t--){
char str1[N],str2[N];//先序,中序
cin>>str1>>str2;
int root = create(str1, str2, strlen(str1));//先序,中序,长度
seq_show(root);
cout<<endl;
}
return 0;
}