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

猜你喜欢

转载自blog.csdn.net/luoshiyong123/article/details/82289288