pat 1110 Complete Binary Tree (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 (≤) 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
解题思路:
这道题开始提交,有三个点通过不了,都显示段错误,想了半天,不应该段错误啊,原来是最开始输入,我用的是char输入,如果节点编号 >= 10那么char读不出来。应该用strng 输入,然后判断是否是" - ",是的话存为-1,否则正常存。
还有就是,判断完全二叉树,用层序遍历,如果前n个遍历序列没有出现-1,说明是完全二叉树,如果前n个序列出现了-1,则表示不是完全二叉树。代码如下
#include<cstdio> #include<cstdlib> #include<cstring> #include<vector> #include<queue> #include<algorithm> using namespace std; int tree[30]; int find(int x){ //寻找节点的根节点 if(tree[x] == x){ return x; } return find(tree[x]); } int main(){ freopen("C:\\Users\\zzloyxt\\Desktop\\1.txt","r",stdin); int n; scanf("%d",&n); for(int i=0;i<n;i++){ //存放每个下标节点的父亲节点。 tree[i] = i; } int left[n]; int right[n]; char a[3],b[3]; for(int i=0;i<n;i++){ scanf("%s %s",a,b); if(strcmp(a,"-") ==0){ left[i] = -1; }else{ int a_int = 0; sscanf(a,"%d",&a_int); left[i] = a_int; tree[a_int] = i; } if(strcmp(b,"-") ==0){ right[i] = -1; }else{ int b_int = 0; sscanf(b,"%d",&b_int); //将字符串转成整数。 right[i] = b_int; tree[b_int] = i; } } int root = find(0); int shu[100] = {0}; //存放层序遍历序列 int index = 0; queue<int> Q; Q.push(root); while(!Q.empty()){ int x = Q.front(); Q.pop(); shu[index++] = x; if(x != -1){ Q.push(left[x]); Q.push(right[x]); } } int flag = 0; for(int i=0;i<n;i++){ if(shu[i] < 0){ flag = 1; break; } } if(flag ==0){ printf("YES %d\n",shu[n-1]); }else{ printf("NO %d\n",root); } return 0; }