PAT甲级真题 1110 Complete Binary Tree (25分) C++实现(判断完全二叉树)

题目

Given a tree, you are supposed to tell if it is a complete binary tree.
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (≤20) which is the total number of nodes in the tree – and hence the nodes are numbered from 0 to N−1. Then N lines follow, each corresponds to a node, and gives the indices of the left and right children of the node. If the child does not exist, a - will be put at the position. Any pair of children are separated by a space.
Output Specification:
For each case, print in one line YES and the index of the last node if the tree is a complete binary tree, or NO and the index of the root if not. There must be exactly one space separating the word and the number.
Sample Input 1:

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

Sample Output 1:

YES 8

Sample Input 2:

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

Sample Output 2:

NO 1

思路

完全二叉树有n/2个非叶子节点,利用队列层序遍历前n/2-1个非叶子节点,它们必须都有两个孩子;最后一个非叶子节点,不能只有右孩子而没有左孩子。

柳神的做法是dfs遍历二叉树,记录层序序列中树的最大下标,如果最大下标==节点数,即为完全二叉树;如果最大下标 > 节点数,说明有空档,不是完全二叉树。

坑点

测试第2、3、4:输入的节点数字可能是两位数(取值<=20),所以不能用char存储,需要用string。

if (l!="-") {
    nodes[i].l = stoi(l);  //输入的数字可能是两位数
    isChild[nodes[i].l] = true;
}

测试点6:当n=1时需要特殊处理,此时一定是完全二叉树。

代码

#include 
#include 
#include 
using namespace std;

struct Node{
    int l, r;
};

int main() {
    int n;
    cin >> n;

    if (n==1){
        cout << "YES 0" << endl;
        return 0;
    }

    vector<Node> nodes(n);
    vector<bool> isChild(n);
    for (int i=0; i<n; i++){
        string l, r;
        cin >> l >> r;
        if (l!="-") {
            nodes[i].l = stoi(l);
            isChild[nodes[i].l] = true;
        }
        else{
            nodes[i].l = -1;
        }
        if (r!="-") {
            nodes[i].r = stoi(r);
            isChild[nodes[i].r] = true;
        }
        else{
            nodes[i].r = -1;
        }
    }

    int root = 0;
    while (isChild[root]) root++;

    bool flag = true;
    queue<int> que;
    que.push(root);
    for (int pNum=n/2; pNum>1; pNum--){
        int p = que.front();
        if (nodes[p].l==-1 || nodes[p].r==-1) {
            flag = false;
            break;
        }
        que.pop();
        que.push(nodes[p].l);
        que.push(nodes[p].r);
    }
    int lastP = que.front();
    if (nodes[lastP].l == -1) flag = false;
    if (flag){
        root = nodes[lastP ].r==-1 ? nodes[lastP].l : nodes[lastP].r; 
        cout << "YES " << root;
    }
    else{
        cout << "NO " << root;
    }
    return 0;
}


你可能感兴趣的:(PAT)