PAT 1110 Complete Binary Tree (25)

1110 Complete Binary Tree (25)(25 分)

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

题目大意:给出一颗二叉树的结构,判断该二叉树是否是完全二叉树;
思路:用数组保存树的结构
在节点中为出现的值就是根节点
层序遍历二叉树, 如果已经出现一个空节点, 如果还出现非空节点, 则该树一定不是完全二叉树;
注意点:开始看输入样例, 误以为输入都是一个字符串,导致三个测试点不能通过, 找了很久的原因, 最多有20个节点, 用string输入就行
 1 #include<iostream>
 2 #include<vector>
 3 #include<queue>
 4 using namespace std;
 5 struct node{ int left, right;};
 6 int main(){
 7   int n, root, i;
 8   cin>>n;
 9   vector<node> v(n);
10   vector<int> vis(n, 0);
11   string a, b;
12   for(i=0; i<n; i++){
13     cin>>a>>b;
14     if(a=="-") v[i].left = -1;
15     else{
16       v[i].left = stoi(a);
17       vis[v[i].left] = 1;
18     }
19     if(b=="-") v[i].right = -1;
20     else{
21       v[i].right = stoi(b);
22       vis[v[i].right] = 1;
23     }
24   }
25   for(i=0; i<n; i++) 
26     if(vis[i]==0) root=i; 
27   queue<int> q;
28   q.push(root);
29   int temp, flag=0, f=0 ;
30   while(q.size()){
31     temp = q.front();
32     q.pop();
33     if(f) break;
34       if(v[temp].left != -1){
35         q.push(v[temp].left);
36         if(flag) f=1;
37       }else flag=1;
38       if(v[temp].right != -1){
39         q.push(v[temp].right);
40         if(flag) f=1;
41       }else flag=1;
42   }
43   if(f) printf("NO %d", root);
44   else printf("YES %d", temp);
45   return 0;
46 }

猜你喜欢

转载自www.cnblogs.com/mr-stn/p/9232618.html