版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Flynn_curry/article/details/61424487
https://www.patest.cn/contests/gplt/L3-010
题意:判断一个树是否是完全二叉搜索树,左大右小。
思路:首先知道什么是完全二叉树。
完全二叉树:只有最下面的两层结点度能够小于2,并且最下面一层的结点都集中在该层最左边的若干位置的二叉树。
这样的话只在层序遍历输出时加以判断即可,剩下的都是普通的建树和遍历。
瞅了一下别人貌似都是用模拟做的。。比赛时这样做可能会费时,不过学学建树过程也是蛮好的。
#include <stdio.h>
#include <algorithm>
#include <string.h>
#include <queue>
#include <iostream>
using namespace std;
typedef long long ll;
const int N = 25;
typedef struct Tree
{
Tree *left;
Tree *right;
int val;
}Tree;
Tree *root;
int seq[N], cnt, n;
Tree *creat(int num)
{
Tree *node = (Tree*)malloc(sizeof(Tree));
node->left = NULL;
node->right = NULL;
node->val = num;
return node;
}
Tree *insertt(Tree *node, int num)
{
if(node == NULL)
{
node = creat(num);
}
else
{
if(num > node->val) node->left = insertt(node->left, num);
else if (num < node->val) node->right = insertt(node->right, num);
}
return node;
}
void levelorder(Tree *cur)
{
queue<Tree*>que;
while(!que.empty()) que.pop();
que.push(cur);
Tree *node;
int flag = 0, vis = 0;//flag判断是否是完全二叉树,vis判断是否访问过
while(!que.empty())
{
node = que.front();
que.pop();
//判断完全二叉树
if(!vis)
{
if((node->left==NULL && node->right==NULL) || (node->left!=NULL && node->right==NULL))
{
flag = 1;
vis = 1;
}
else if(node->left==NULL && node->right!=NULL)
{
flag = 0;
vis = 1;
}
}
else
{
if(node->left!=NULL || node->right!=NULL) flag = 0;
}
if(cnt == n-1) printf("%d\n", node->val);
else
{
printf("%d ", node->val);
cnt++;
}
if(node->left != NULL) que.push(node->left);
if(node->right != NULL) que.push(node->right);
}
if(flag) printf("YES\n");
else printf("NO\n");
}
void build()
{
root = NULL;
cnt = 0;
for(int i = 0; i < n; i++)
{
int num = seq[i];
root = insertt(root, num);
}
}
int main()
{
// freopen("in.txt", "r", stdin);
while(~scanf("%d", &n))
{
for(int i = 0; i < n; i++)
scanf("%d", &seq[i]);
build();
levelorder(root);
}
}