#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <stack>
#include <queue>
#include <map>
using namespace std;
const int maxn=100010;
int n;
int d[maxn],preo[maxn],post[maxn],ind = 0,ind1 = 0,ind2 = 0;
struct node
{
int data;
node* l;
node* r;
};
node* newNode(int x)
{
node* N = new node;
N->data = x;
N->l = N->r = NULL;
return N;
}
void insertT(node* &root,int x) //插入节点,按照左小右大于等于
{
if(root == NULL)
{
root = newNode(x);
return ;
}
if(root->data <= x)
{
insertT(root->r,x);
}
else
insertT(root->l,x);
// return;
}
void preoder(node* root)
{
if(root == NULL)
return;
// printf("%d",root->data);
preo[ind1++] = root->data;
preoder(root->l);
preoder(root->r);
}
void postoder(node* root)
{
if(root == NULL)
return;
postoder(root->l);
postoder(root->r);
// printf("%d",root->data);
post[ind2++] = root->data;
}
void switchnode(node* &root) //交换左右节点
{
if(root == NULL)
return;
node* temp = root->l;
root->l = root->r;
root->r = temp;
switchnode(root->l);
switchnode(root->r);
}
int main()
{
// freopen("1.txt","r",stdin);
node* root = new node;
root = NULL;
scanf("%d",&n);
for(int i = 0;i<n;i++)
{
int temp;
scanf("%d",&temp);
d[ind++] = temp; //记录原来的数组,其实用vector比较更方便
insertT(root,temp); //插入到bst
}
preoder(root);
int flag = 0;
for(int i = 0;i<ind;i++)
{
if(d[i] != preo[i])
{
flag = 1; //和先序遍历结果不一致
break;
}
}
if(flag == 1) //如果和先序编录结果不一致就去检查镜像树
{
flag = 0;
switchnode(root);
ind1 = 0;
preoder(root);
for(int i = 0;i<ind;i++)
{
if(d[i] != preo[i])
{
flag = 2; //和镜像树也不一致
break;
}
}
}
if(flag == 1 || flag == 2) //都不一致
printf("NO");
if(flag == 0)
{
printf("YES\n");
postoder(root);
for(int i = 0;i<n;i++)
{
printf("%d",post[i]);
if(i!=n-1)
printf(" ");
}
}
}
1043 Is It a Binary Search Tree (25分) (BST)
最新推荐文章于 2020-05-31 09:19:39 发布