A1043 Is It a Binary Search Tree (25 分| 二叉查找树,附详细注释,逻辑分析)
其他
2020-03-28 11:25:09
阅读次数: 0
写在前面
- 思路分析
- 给定1个整数键值序列,问这个序列是不是这个二叉搜索树的先序或者是这个二叉树镜像树的先序
- 实现分析:
- 假设是二叉搜索树,开始isMirror为FALSE,根据二叉搜索树的性质将已知的前序转换为后序
- 转换过程中,如果发现最后输出后序数组长度不为n,那就设isMirror为true,然后清空后序数
组,重新再转换1次(根据镜面二叉搜索树性质)
- 如果依旧转换后数组大小不不等于n,就输出no否则输出yes
- 热点知识,学习ing
测试用例
ac代码
-
#include<bits/stdc++.h>
using namespace std;
vector<int>pre,post,vec;
int n,x;
struct node
{
int data;
node *left,*right;
};
struct node *root = NULL;
void Insert(node * &root,int data)
{
if(root == NULL)
{
root = new node();
root->data = x;
root->left = root ->right =NULL;
}else if(data < root->data)
Insert(root->left,data);
else if(data >= root->data)
Insert(root->right,data);
}
void preorder1(node * root)
{
if(root)
{
pre.push_back(root->data);
preorder1(root->left);
preorder1(root->right);
}
}
void preorder2(node * root)
{
if(root)
{
pre.push_back(root->data);
preorder2(root->right);
preorder2(root->left);
}
}
void postorder1(node * root)
{
if(root)
{
postorder1(root->left);
postorder1(root->right);
post.push_back(root->data);
}
}
void postorder2(node * root)
{
if(root)
{
postorder2(root->right);
postorder2(root->left);
post.push_back(root->data);
}
}
int main()
{
scanf("%d",&n);
for(int i = 1; i <= n; i++)
{
scanf("%d",&x);
vec.push_back(x);
Insert(root,x);
}
pre.clear();
preorder1(root);
int i;
for(i = 0; i < n;i++ )
{
if(vec[i] != pre[i])
break;
}
if(i == n)
{
printf("YES\n");
postorder1(root);
for(int j = 0 ; j < n;j++)
printf("%d%c",post[j]," \n"[j==n-1]);
return 0;
}
pre.clear();
preorder2(root);
for(i = 0; i < n;i++ )
{
if(vec[i] != pre[i])
break;
}
if(i == n)
{
printf("YES\n");
postorder2(root);
for(int j = 0 ; j < n;j++)
printf("%d%c",post[j]," \n"[j==n-1]);
return 0;
}
printf("NO\n");
return 0;
}
发布了328 篇原创文章 ·
获赞 107 ·
访问量 39万+
转载自blog.csdn.net/qq_24452475/article/details/100619924