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   scanf("%d", &n);
 9   vector<node> v(n);
10   //记录出现过的节点
11   vector<int> vis(n, 0);
12   string a, b;
13   for(i=0; i<n; i++){
14     cin>>a>>b;
15     if(a=="-") v[i].left = -1;
16     else{
17       v[i].left = stoi(a);
18       vis[v[i].left] = 1;
19     }
20     if(b=="-") v[i].right = -1;
21     else{
22       v[i].right = stoi(b);
23       vis[v[i].right] = 1;
24     }
25   }
26   for(i=0; i<n; i++) //没有出现过在子节点中的点就是根节点
27     if(vis[i]==0) root=i; 
28   queue<int> q;
29   q.push(root);
30   int temp, flag=0, f=0 ;
31   //flag:记录是否出现空节点
32   //f:记录出现空节点后, 是否还有后继的节点
33   while(q.size()){
34     temp = q.front();
35     q.pop();
36     if(f) break;
37       if(v[temp].left != -1){
38         q.push(v[temp].left);
39         if(flag) f=1;
40       }else flag=1;
41       if(v[temp].right != -1){
42         q.push(v[temp].right);
43         if(flag) f=1;
44       }else flag=1;
45   }
46   if(f) printf("NO %d", root);
47   else printf("YES %d", temp);
48   return 0;
49 }
有疑惑或者更好的解决方法的朋友,可以联系我,大家一起探讨。qq:1546431565
原文地址:https://www.cnblogs.com/mr-stn/p/9232618.html