PAT1110:Complete Binary Tree

1110. Complete Binary Tree (25)

时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

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和遍历次数cnt是否相等,相等yes,不想等no。
注意:输入用string而不用char,因为char不能表示两位数以上的数字。之前没注意导致代码只有部分ac。

代码

 

#include<iostream>
#include<vector>
#include<queue>
using namespace std;

class Node
{
public:
    int left;
    int right;
};
int main()
{
    int N;
    while(cin >> N)
    {
      vector<Node> nodes(N);
      vector<bool> isroot(N,true);
      //Build tree
      for(int i = 0;i < N;i++)
      {
          string left,right;
          cin >> left >> right;
          if(left == "-")
            nodes[i].left = -1;
          else
          {
            nodes[i].left = stoi(left);
            isroot[nodes[i].left] = false;
          }
          if(right == "-")
            nodes[i].right = -1;
          else
          {
            nodes[i].right = stoi(right);
            isroot[nodes[i].right] = false;
          }
      }
      //Find root
      int root = -1;
      for(int i = 0;i < isroot.size();i++)
      {
          if(isroot[i])
          {
            root = i;
            break;
          }
      }
      //BFS
      queue<int> q;
      q.push(root);
      int cnt = 0,lastindex = -1;
      while(!q.empty())
      {
          int tmp = q.front();
          q.pop();
          if(tmp == -1)
          {
              break;
          }
          cnt++;
          lastindex = tmp;
          q.push(nodes[tmp].left);
          q.push(nodes[tmp].right);
      }
      //Output
      if(cnt == N)
        cout << "YES" << " " << lastindex <<endl;
      else
        cout << "NO" << " " << root << endl;
    }
}

  

posted @ 2017-11-04 19:54  0kk470  阅读(237)  评论(0编辑  收藏  举报