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


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);
    }
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值