Binary search tree of attack

Posted by PeterPopper on Thu, 02 Apr 2020 11:24:37 +0200

Problem Description
Given two permutations of 1-N, two binary search trees are constructed by using these two permutations (that is, by inserting sequence elements into an empty tree in turn). If the two binary search trees are identical, then YES is output; otherwise, NO is output. After that, the post sequence and sequence sequence of the first binary search tree are output.

Input
A set of data in each input file.

The first line is a positive integer N (1 < = N < = 30), which indicates the number of nodes in the binary search tree.

The next two lines represent two permutations of 1-n.

Output
If the binary search trees represented by the two permutations are identical, a row of YES will be output, otherwise a row of NO will be output.

The next two lines respectively output the post sequence and sequence sequence sequence of the first binary search tree, and the integers are separated by spaces.

Extra spaces are not allowed at the end of each line.

Sample Input
5
4 2 1 3 5
4 5 2 3 1

Sample Output
YES
1 3 2 5 4
4 2 5 1 3

Author
Shoutmon

Source
16 Zhejiang University postgraduate entrance examination machine test simulation competition

```#include <iostream>
#include <cstdio>
#include <queue>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left,*right;
TreeNode(int e):val(e),left(NULL),right(NULL){}
};
int n,e;
TreeNode * insert(TreeNode *r,int e)
{
if(r==NULL) return new TreeNode(e);
if(e<r->val) r->left=insert(r->left,e);
else r->right=insert(r->right,e);
return r;
}
bool issame(TreeNode *r1,TreeNode *r2)
{
if(!r1&&!r2) return true;
if(r1&&r2) return r1->val==r2->val&&issame(r1->left,r2->left)&&issame(r1->right,r2->right);
return false;
}
void postra(TreeNode *r,int &w)
{
if(r){
postra(r->left,w);
postra(r->right,w);
++w==n?printf("%d\n",r->val):printf("%d ",r->val);
}
}
void levtra(TreeNode *r)
{
queue<TreeNode *> q;
q.push(r);
int w=0;
while(!q.empty())
{
TreeNode *s=q.front();
q.pop();
++w==n?printf("%d\n",s->val):printf("%d ",s->val);
if(s->left) q.push(s->left);
if(s->right) q.push(s->right);
}
}
int main()
{
scanf("%d",&n);
TreeNode *r1=NULL,*r2=NULL;
for(int i=0;i<n;++i){
scanf("%d",&e);
r1=insert(r1,e);
}
for(int i=0;i<n;++i){
scanf("%d",&e);
r2=insert(r2,e);
}
bool res=issame(r1,r2);
res?printf("YES\n"):printf("NO\n");
int w=0;
postra(r1,w);
levtra(r1);
return 0;
}```