假设一个二叉树上所有结点的权值都互不相同。
我们可以通过后序遍历和中序遍历来确定唯一二叉树。
也可以通过前序遍历和中序遍历来确定唯一二叉树。
但是,如果只通过前序遍历和后序遍历,则有可能无法确定唯一二叉树。
现在,给定一组前序遍历和后序遍历,请你输出对应二叉树的中序遍历。
如果树不是唯一的,则输出任意一种可能树的中序遍历即可。
输入格式
第一行包含整数 N,表示结点数量。
第二行给出前序遍历序列。
第三行给出后序遍历序列。
一行中的数字都用空格隔开。
输出格式
首先第一行,如果树唯一,则输出 Yes,如果不唯一,则输出 No。
然后在第二行,输出树的中序遍历。
注意,如果树不唯一,则输出任意一种可能的情况均可。
数据范围
1≤N≤30
输入样例1:
7
1 2 3 4 6 7 5
2 6 7 4 5 3 1
输出样例1:
Yes
2 1 6 4 7 3 5
输入样例2:
4
1 2 3 4
2 4 3 1
输出样例2:
No
2 1 3 4
依旧是建树
#include <bits/stdc++.h>
using namespace std;
int pre[1010],post[1010];
struct node
{
int data;
struct node*l,*r;
};
int n;
bool is=true;
int num;
void zhongxv(struct node*root)
{
if(root)
{
zhongxv(root->l);
num++;
cout <<root->data;
if(num!=n)
cout <<" ";
zhongxv(root->r);
}
}
struct node*create(int h1,int h2,int len)
{
if(len==0)
return NULL;
struct node*p ;
p = new node;
p->data=pre[h1];
// cout <<pre[h1]<<endl;
if(len==1)
return p;
int i;
for( i=h2;post[i]!=pre[h1+1];i++);
int l1 = i-h2+1;
int l2 = len-1-l1;
if(l2 == 0)
is=false;
p->l = create(h1+1,h2,l1);
p->r = create(h1+l1+1,i+1,l2);
return p;
}
int main()
{
cin >> n;
for(int i=1;i<=n;i++)
cin >>pre[i];
for(int i=1;i<=n;i++)
cin >>post[i];
struct node*root;
root=create(1,1,n);
if(is==true)
cout <<"Yes"<<endl;
else
cout <<"No"<<endl;
zhongxv(root);
cout <<endl;
return 0;
}