L3-010 是否完全二叉搜索树 (30 分)

在这里插入图片描述
根据节点的编号判断是否是完全二叉搜索树,如果最大的节点编号不等于n就不是,否则就是。

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <string>
#include <cstring>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <sstream>
#define ll long long
#define lowbit(x) ((~x+1)&x)
#define inf 0x3f3f3f3f
using namespace std;
struct node {
    struct node *l,*r;
    int val;
};
int n,m,num;

struct node *build(struct node *root,int w,int in) {
    if(root==NULL) {
        root = (struct node *)malloc(sizeof(struct node));
        root->val = w;
        root->l = NULL;
        root->r = NULL;
        num = max(num,in);
        return root;
    }
    if(root->val > w) root->r=build(root->r,w,in<<1|1);
    else root->l = build(root->l,w,in<<1);
    return root;
}

void bfs(struct node *root) {
    queue<node*>q;
    q.push(root);
    cout<<root->val;
    while(!q.empty()) {
        struct node *top;
        top=q.front();
        q.pop();
        if(top->l) {
            cout<<' '<<top->l->val;
            q.push(top->l);
        }
        if(top->r) {
            cout<<' '<<top->r->val;
            q.push(top->r);
        }
    }
}

int main() {
    cin>>n;
    struct node *root;
    root = (struct node *)malloc(sizeof(struct node));
    root=NULL;
    for(int i=1; i<=n; i++) {
        int k;
        cin>>k;
        root = build(root,k,1);
    }
    bfs(root);
    cout<<endl;
    if(num==n) cout<<"YES"<<endl;
    else cout<<"NO"<<endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值