PAT (Advanced Level) Practice A1110 Complete Binary Tree (25 分)(C++)(甲级)(判断是否为完全二叉树,sscanf)

版权声明:假装有个原创声明……虽然少许博文不属于完全原创,但也是自己辛辛苦苦总结的,转载请注明出处,感谢! https://blog.csdn.net/m0_37454852/article/details/88190084

原题链接

#include<algorithm>
#include<algorithm>
#include<iostream>
#include<cstdio>
#include<cstring>
#include <ctime>
#include <cmath>
#include <vector>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <deque>
using namespace std;

typedef struct BiTNode
{
    int data;//存放索引号
    bool isRoot;//是否为根节点标志
    struct BiTNode *lChild, *rChild;
}BiTNode, *BiTree;
const int MAX = 50;
BiTree P[MAX];

bool isComplete(BiTree ROOT, BiTree &LAST)//判断是否为完全二叉树,若是则用LAST返回其最后一个节点
{//判断标准是,层次遍历,若某节点无孩子后,之后不应再有孩子;否则不是完全二叉树
    queue<BiTree> Q;
    BiTree T = ROOT;
    Q.push(T);
    int flag = 0;
    while(!Q.empty())
    {
        T = Q.front();
        LAST = T;
        Q.pop();
        if(T->lChild)
        {
            Q.push(T->lChild);
            if(flag) return false;
        }
        else flag = 1;
        if(T->rChild)
        {
            Q.push(T->rChild);
            if(flag) return false;
        }
        else flag = 1;
    }
    return true;
}

int main()
{
    int N;
    scanf("%d", &N);
    for(int i=0; i<N; i++)//初始化
    {
        P[i] = new BiTNode;
        P[i]->isRoot = 1;
    }
    for(int i=0; i<N; i++)
    {
        char str1[5], str2[5];
        scanf("%s %s", str1, str2);//由于索引号可能是多位的,不能用char接收
        P[i]->data = i;
        if(!strcmp(str1, "-")) P[i]->lChild = NULL;//空
        else
        {
            int num = 0;
            sscanf(str1, "%d", &num);//用sscanf写入num
            P[i]->lChild = P[num];
            P[num]->isRoot = 0;//孩子不是根节点
        }
        if(!strcmp(str2, "-")) P[i]->rChild = NULL;
        else
        {
            int num = 0;
            sscanf(str2, "%d", &num);
            P[i]->rChild = P[num];
            P[num]->isRoot = 0;
        }
    }
    int T = 0;
    while(T < N && !P[T]->isRoot) T++;
    BiTree ROOT = P[T], LAST = ROOT;//找出根节点
    if(isComplete(ROOT, LAST)) printf("YES %d\n", LAST->data);
    else printf("NO %d\n", ROOT->data);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/m0_37454852/article/details/88190084