题目大意:
给出二叉查找树的节点输入序列,判断这个序列是否为二叉查找树或者镜像(交换左右子节点位置)二叉查找树的先序序列,如果是,输出后序遍历序列。
解题思路:
按照题目要求构建二叉查找树然后先序遍历得到结果对比即可,为了方便比较两个序列采用vector方便一些,关于镜像二叉查找树只需要写遍历的时候将左右反过来即可。
代码如下:
#include<iostream>
#include<cstdio>
#include<fstream>
#include<set>
#include<cmath>
#include<cstring>
#include<string>
#include<map>
#include<vector>
#include<iomanip>
#include<cstdlib>
#include<list>
#include<queue>
#include<stack>
#include<algorithm>
#define inf 0x3f3f3f3f
#define MOD 1000000007
#define mem0(a) memset(a,0,sizeof(a))
#define mem1(a) memset(a,-1,sizeof(a))
#define meminf(a) memset(a,inf,sizeof(a))
//vector ::iterator it;
//set<int>::iterator iter;
typedef long long ll;
typedef unsigned long long ull;
using namespace std;
int n;
vector<int>pre,bst,mbst;//插入序列,原树先序遍历,翻转后的先序遍历
struct node
{
int data;
node* lchild;
node* rchild;
};
node* newnode(int data)//构建新节点
{
node* root=new node;
root->data=data;
root->lchild=root->rchild=NULL;
return root;
}
void insert(node* &root,int data)//插入BST
{
if(root==NULL)
{
root=newnode(data);
return ;
}
if(data<root->data) insert(root->lchild,data);
else insert(root->rchild,data);
}
void preorder1(node* root)//原树的先序遍历
{
if(root==NULL)return;
bst.push_back(root->data);
preorder1(root->lchild);
preorder1(root->rchild);
}
void preorder2(node* root)//翻转后的先序遍历
{
if(root==NULL)return;
mbst.push_back(root->data);
preorder2(root->rchild);
preorder2(root->lchild);
}
int count1;
void postorder1(node* root)//原树的后序遍历
{
if(root==NULL)return;
postorder1(root->lchild);
postorder1(root->rchild);
printf("%d",root->data);
count1++;
if(count1<n)printf(" ");
}
void postorder2(node* root)//翻转后树的后序遍历
{
if(root==NULL)return;
postorder2(root->rchild);
postorder2(root->lchild);
printf("%d",root->data);
count1++;
if(count1<n)printf(" ");
}
int main()
{
// std::ios::sync_with_stdio(false);
// cin.tie(0);
// freopen("test.txt","r",stdin);
// freopen("output.txt","w",stdout);
scanf("%d",&n);
node* root=NULL;
for(int i=0;i<n;i++)
{
int tmp;
scanf("%d",&tmp);
pre.push_back(tmp);
insert(root,tmp);
}
preorder1(root);
preorder2(root);
if(pre==bst)
{
printf("YES\n");
postorder1(root);
}
else if(pre==mbst)
{
printf("YES\n");
postorder2(root);
}
else printf("NO");
printf("\n");
return 0;
}