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个结点。
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int n,v[30],root = -1,q[30],head = 0,tail = 0;
char l[3],r[3];
struct Node
{
    int left,right;
}s[30];
int main()
{
    cin>>n;
    for(int i = 0;i < n;i ++)
    {
        cin.get();
        cin>>l;
        if(strcmp(l,"-") == 0)s[i].left = -1;
        else
        {
            int d = 0;
            for(int j = 0;l[j];j ++)
                d = d * 10 + l[j] - '0';
            s[i].left = d;
            v[d] = 1;
        }
        cin.get();
        cin>>r;
        if(strcmp(r,"-") == 0)s[i].right = -1;
        else
        {
            int d = 0;
            for(int j = 0;r[j];j ++)
                d = d * 10 + r[j] - '0';
            s[i].right = d;
            v[d] = 1;
        }
    }
    for(int i = 0;i < n;i ++)
    if(!v[i])
    {
        root = i;
        break;
    }
    q[tail ++] = root;
    while(head < tail)
    {
        if(s[q[head]].left != -1)q[tail ++] = s[q[head]].left;
        else break;
        if(s[q[head]].right != -1)q[tail ++] = s[q[head]].right;
        else break;
        head ++;
    }
    if(tail == n)cout<<"YES "<<q[tail - 1];
    else cout<<"NO "<<root;
}