PAT(Advanced)1110 Complete Binary Tree C++实现

PAT(Advanced)甲级1110 Complete Binary Tree C++实现

题目链接

1110 Complete Binary Tree

题目大意

从0到N-1个节点,给定每个节点的左右孩子,求给定二叉树是否为完全二叉树,若是则输出YES以及最右边的叶子节点的序号,否则输出NO以及根节点序号

算法思路

根据题意要求和输入数据,先找到二叉树根节点,即没有父亲节点的节点,根据完全二叉树性质和层序遍历定义,对完全二叉树进行层序遍历,将包括空指针的所有的节点入队,若遇到第一个空指针,则后面必然没有结点,即后面若有节点则必然为空,否则不是完全二叉树。

AC代码

/*
author : eclipse
email  : eclipsecs@qq.com
time   : Fri Jun 26 19:02:33 2020
*/
#include <bits/stdc++.h>
using namespace std;

struct Node {
    int left;
    int right;
};

vector<Node> binaryTree;
int root;
int indexValue;

bool levelOrderTraverse() {
    queue<int> q;
    q.push(root);
    while (!q.empty()) {
        int front = q.front();
        q.pop();
        if (front == -1) {
            while (!q.empty()) {
                if (q.front() != -1) {
                    indexValue = root;
                    return false;
                }
                q.pop();
            }
        } else {
            indexValue = front;
            q.push(binaryTree[front].left);
            q.push(binaryTree[front].right);
        }
    }
    return true;
}

int main(int argc, char const *argv[]) {
    int N;
    scanf("%d", &N);
    binaryTree.resize(N);
    vector<bool> children;
    children.resize(N);
    for (int i = 0; i < N; i++) {
        string left, right;
        cin >> left >> right;
        if (left == "-") {
            binaryTree[i].left = -1;
        } else {
            int child = atoi(left.c_str());
            children[child] = true;
            binaryTree[i].left = child;
        }
        if (right == "-") {
            binaryTree[i].right = -1;
        } else {
            int child = atoi(right.c_str());
            children[child] = true;
            binaryTree[i].right = child;
        }
    }
    for (int i = 0; i < children.size(); i++) {
        if (!children[i]) {
            root = i;
            break;
        }
    }
    printf("%s ", (levelOrderTraverse() ? "YES" : "NO"));
    printf("%d", indexValue);
    return 0;
}

样例输入1

9
7 8
- -
- -
- -
0 1
2 3
4 5
- -
- -

样例输出1

YES 8

样例输入2

8
- -
4 5
0 6
- -
2 3
- 7
- -
- -

样例输出2

NO 1

鸣谢

PAT

最后

  • 由于博主水平有限,不免有疏漏之处,欢迎读者随时批评指正,以免造成不必要的误解!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值