您的位置:首页 > 其它

gplt L3-010. 是否完全二叉搜索树(判断完全BST)

2017-03-11 19:17 337 查看
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
, 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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  天梯赛