#include <cstdio>
#include <cstdlib>
#include <string.h>
#include <cmath>
#include <algorithm>
#include <string>
#include <iostream>
#include <vector>
#include <set>
#include <map>
#include <stack>
#include <queue>
using namespace std;
struct node
{
int data;
node* lchild;
node* rchild;
};
int a[1010],N,b[1010],index;
node* newNode(int x)
{
node* Node=new node;
Node->data=x;
Node->lchild=Node->rchild=NULL;
return Node;
}
void insert(node* &root,int x)
{
if(root==NULL)
{
root=newNode(x);
return;
}
else if(x>=root->data)
{
insert(root->rchild,x);
}
else if(x<root->data)
{
insert(root->lchild,x);
}
}
node* Create(int a[],int n)
{
node* root=NULL;
for(int i=0;i<n;i++)
{
insert(root,a[i]);
}
return root;
}
void PreOrder(node* root)
{
if(root==NULL)return;
b[index++]=root->data;
PreOrder(root->lchild);
PreOrder(root->rchild);
}
void PreOrderIn(node* root)
{
if(root==NULL)return;
b[index++]=root->data;
PreOrderIn(root->rchild);
PreOrderIn(root->lchild);
}
void postOrder(node* root,bool In)
{
if(root==NULL)return;
if(!In)
{
postOrder(root->lchild,In);
postOrder(root->rchild,In);
}
else
{
postOrder(root->rchild,In);
postOrder(root->lchild,In);
}
printf("%d",root->data);
if(index!=N-1)
printf(" ");
index++;
}
bool cmpab(int a[],int b[] ,int n)
{
for(int i=0;i<n;i++)
{
if(a[i]!=b[i])
return false;
}
return true;
}
int main()
{
scanf("%d",&N);
for(int i=0;i<N;i++)
{
scanf("%d",&a[i]);
}
node* root=Create(a,N);
index=0;
PreOrder(root);
bool Flag=false;
bool In=false;
if(cmpab(a,b,N))
{
Flag=true;
}
else
{
index=0;
PreOrderIn(root);
if(cmpab(a,b,N))
{
Flag=true;
In=true;
}
}
if(Flag)
{
printf("YES\n");
index=0;
postOrder(root,In);
}
else
{
printf("NO\n");
}
system("pause");
return 0;
}
PAT甲1043. Is It a Binary Search Tree (25)
猜你喜欢
转载自blog.csdn.net/yhy489275918/article/details/80171009
今日推荐
周排行