PAT A1110 Complete Binary Tree(25 分)----判断是否完全二叉树

总结:

1.这道题很简单,但是我第一次只得了18/25.做简单题的时候一定要细心。

2.当表示没有孩子的时候用-,所以开始很自然的想到用char读取,但是注意孩子的序号完全可能为两位数,11,12.所以用string读取。

代码:

#include<iostream>
#include<vector>
#include<map>
#include<string>
#include<queue>
using namespace std;
int ps[1000];
struct node
{
    int left, right;
    node()
    {}
};
struct node2{
    int index;
    int p;
};
map<int,node>pp;
int main()
{
    int n;
    cin >> n;
    for (int i = 0; i < n; i++)
    {
        string a, b;
        cin >> a>>b;
        if (a != "-"){ pp[i].left= stoi(a); ps[pp[i].left] = 1; }
        else pp[i].left = -1;
        if (b !="-"){ pp[i].right= stoi(b); ps[pp[i].right] = 1; }
        else pp[i].right = -1;
    }
    int root = -1;
    for (int i = 0; i < n;i++)
    if (ps[i] != 1)root = i;
    int ufo[1000];  queue<node2> dui;
    fill(ufo, ufo + n,-1);
    node2 ka; ka.index = 0; ka.p = root; ufo[ka.index] =ka.p;
    dui.push(ka);
    while (!dui.empty()){
        node2 root1 = dui.front();
        dui.pop();
        if (pp[root1.p].left != -1&&2*root1.index+1<n){ ufo[2 * root1.index + 1] = pp[root1.p].left; node2 s1; s1.index = 2 * root1.index + 1; s1.p = pp[root1.p].left; dui.push(s1); }
        if (pp[root1.p].right != -1&&2*root1.index+2<n){ ufo[2 * root1.index + 2] = pp[root1.p].right; node2 s2; s2.index = 2 * root1.index + 2; s2.p = pp[root1.p].right; dui.push(s2); }
    }
    bool flag = true;
    int last = -1;
    for (int i = 0; i < n; i++)
    {
        if (ufo[i] == -1){ flag = false; break; }
    }
    if (flag == true){ cout << "YES" <<" "<< ufo[n-1]; }
    else{ cout << "NO" << " " << root; }
    
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值