1043 Is It a Binary Search Tree

在这里插入图片描述在这里插入图片描述

题目大意:

给出二叉查找树的节点输入序列,判断这个序列是否为二叉查找树或者镜像(交换左右子节点位置)二叉查找树的先序序列,如果是,输出后序遍历序列。

解题思路:

按照题目要求构建二叉查找树然后先序遍历得到结果对比即可,为了方便比较两个序列采用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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值