数组模拟链接见下
sdut oj 求二叉树的层次遍历(先序中序->二叉树 层序输出)(数组模拟).
链表题解见下文
Description
已知一颗二叉树的前序遍历和中序遍历,求二叉树的层次遍历。
Input
输入数据有多组,输入T,代表有T组测试数据。每组数据有两个长度小于50的字符串,第一个字符串为前序遍历,第二个为中序遍历。
Output
每组输出这颗二叉树的层次遍历。
Sample
Input
2
abc
bac
abdec
dbeac
Output
abc
abcde
C++
/*
time : 2021年6月23日23:42:29
result : accept
author : kirie
tips : null
*/
#include <iostream>
#include <cstring>
#include <queue>
#define mem(a,b) memset(a,b,sizeof(a))
using namespace std;
const int N = 107;
typedef struct TreeNode{
char val;
struct TreeNode* LChild;
struct TreeNode* RChild;
}Node;
Node* CreateTree(char pre[], char mid[], int len){
if(len <= 0)
return NULL;
Node *root = new Node;
root->val = pre[0];
int i;
for(i = 0;i < len; i++){
if(mid[i] == pre[0])
break;
}
root->LChild = CreateTree(pre+1, mid, i);
root->RChild = CreateTree(pre+1+i, mid+1+i, len-i-1);
return root;
}
void lev_show(Node* root){
queue<Node*>que;
Node* t;
if(!root)
return ;
que.push(root);
while(!que.empty()){
t = que.front();
que.pop();
cout<<t->val;
if(t->LChild)
que.push(t->LChild);
if(t->RChild)
que.push(t->RChild);
}
}
int main()
{
int t;
cin>>t;
while(t--){
char str1[N],str2[N];
cin>>str1>>str2;
Node* root = new Node;
root = CreateTree(str1, str2, strlen(str1));
lev_show(root);
cout<<endl;
}
return 0;
}