Given the post-order traversal and middle-order traversal of a binary tree, please output the sequence of its layer-order traversal. It is assumed that the key values are all positive integers that are not equal to each other.
Input format:
Enter the first line to give a positive integer N (≤30), which is the number of nodes in the binary tree. The second line gives the subsequent traversal sequence. The third line gives the in-order traversal sequence. The numbers are separated by spaces.
Output format:
Output the sequence traversed by the tree in one line. The numbers are separated by 1 space, and there must be no extra spaces at the beginning and end of the line.
Input sample:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
Sample output:
4 1 6 3 5 7 2
------------------------------------------
Contribute
void rec(int L,int R,int n)
{
if(L>=R)
return;
T[n].value=post[pos--];
T[n].left=2*n;
T[n].right=2*n+1;
int mid;
for(mid=L;mid<R;mid++)
{
if (in[mid]==T[n].value)//Find the position of the root node in the middle order traversal
{
break;
}
}
The right side of the root node is the right subtree
rec(mid+1,R,2*n+1);//Build the right subtree
Left subtree of the root node
rec(L,mid,2*n);//Create a left subtree
}
-------------------------------------------
Level traversal
void bfs()
{
queue<int>q;
q.push(1);//Root node sequence number
while (!q.empty())
{
node cur=T[q.front()];//Current node
q.pop();//The current node pops the stack
if(indx==1)
{
cout<<cur.value;
indx++;
}
else
{
cout<<" "<<cur.value;
}
if(T[cur.left].value!=-1)
q.push(cur.left);//The sequence number of the left subtree node is pushed into the stack
if(T[cur.right].value!=-1)
q.push(cur.right);//The sequence number of the right subtree node is pushed into the stack
}
}
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<set>
#include<queue>
#include<stack>
using namespace std;
const int maxn = 10000;
int post[maxn],in[maxn];
struct node
{
int value,left,right;
}T[maxn];
int pos;
void rec(int L,int R,int n)
{
if(L>=R)
return;
T[n].value=post[pos--];
T[n].left=2*n;
T[n].right=2*n+1;
int mid;
for(mid=L;mid<R;mid++)
{
if(in[mid]==T[n].value)
{
break;
}
}
rec(mid+1,R,2*n+1);//建立右子树
rec(L,mid,2*n);//建立左子树
}
int indx=1;
void bfs()
{
queue<int>q;
q.push(1);
while (!q.empty())
{
node cur=T[q.front()];
q.pop();
if(indx==1)
{
cout<<cur.value;
indx++;
}
else
{
cout<<" "<<cur.value;
}
if(T[cur.left].value!=-1)
q.push(cur.left);
if(T[cur.right].value!=-1)
q.push(cur.right);
}
}
int main()
{
int N;
cin>>N;
for(int i=0;i<N;i++)
{
cin>>post[i];
}
for(int i=0;i<N;i++)
{
cin>>in[i];
}
memset(T,-1,sizeof(T));
pos=N-1;
rec(0,N,1);
bfs();//层序遍历
return 0;
}