1119. Pre- and Post-order Traversals (30)
Suppose that all the keys in a binary tree are distinct positive integers. A unique binary tree can be determined by a given pair of postorder and inorder traversal sequences, or preorder and inorder traversal sequences. However, if only the postorder and preorder traversal sequences are given, the corresponding tree may no longer be unique.
Now given a pair of postorder and preorder traversal sequences, you are supposed to output the corresponding inorder traversal sequence of the tree. If the tree is not unique, simply output any one of them.
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (<=30), the total number of nodes in the binary tree. The second line gives the preorder sequence and the third line gives the postorder sequence. All the numbers in a line are separated by a space.
Output Specification:
For each test case, first printf in a line "Yes" if the tree is unique, or "No" if not. Then print in the next line the inorder traversal sequence of the corresponding binary tree. If the solution is not unique, any answer would do. It is guaranteed that at least one solution exists. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the end of the line.
Sample Input 1:7 1 2 3 4 6 7 5 2 6 7 4 5 3 1Sample Output 1:
Yes 2 1 6 4 7 3 5Sample Input 2:
4 1 2 3 4 2 4 3 1Sample Output 2:
No 2 1 3 4
老有乱码啊,改来改去。
前序列中第二个元素为左子树的树根,找到后序列中对应的下标,递归得到一个解。
后序列中倒数二个元素为右子树的树根,找到前序列中对应的下标,递归得到一个解。
注意下标对齐。
#include<iostream>
#include<vector>
using namespace std;
vector<int>a;
vector<int>b;
vector<int>ansa;
vector<int>ansb;
void builda(int al,int ar,int bl,int br)
{
int idx;
for(int i=al;i<=ar;i++)
if(a[i]==b[br-1])
idx=i;
if(al+1<idx-1)
builda(al+1,idx-1,bl,bl+idx-2-al);
else if(al+1==idx-1)
ansa.push_back(a[al+1]);
ansa.push_back(a[al]);
if(idx<ar)
builda(idx,ar,br-1-ar+idx,br-1);
else if(idx==ar)
ansa.push_back(a[idx]);
}
void buildb(int al,int ar,int bl,int br)
{
int idx;
for(int i=bl;i<=br;i++)
if(a[al+1]==b[i])
idx=i;
if(bl<idx)
buildb(al+1,al+1+idx-bl,bl,idx);
else if(bl==idx)
ansb.push_back(b[bl]);
ansb.push_back(b[br]);
if(idx+1<br-1)
buildb(ar-br+idx+2,ar,idx+1,br-1);
else if(idx+1==br-1)
ansb.push_back(b[idx+1]);
}
int main()
{
int n;
cin>>n;
for(int i=0;i<n;i++)
{
int num;
cin>>num;
a.push_back(num);
}
for(int i=0;i<n;i++)
{
int num;
cin>>num;
b.push_back(num);
}
if(n==1)
{
cout<<"Yes"<<endl;
cout<<a[0]<<endl;
return 0;
}
builda(0,n-1,0,n-1);
buildb(0,n-1,0,n-1);
if(ansb==ansa)
cout<<"Yes"<<endl;
else
cout<<"No"<<endl;
cout<<ansa[0];
for(int i=1;i<ansa.size();i++)
cout<<" "<<ansa[i];
cout<<endl;
return 0;
}