1110. Complete Binary Tree (25)

来源:互联网 发布:jojo超像可动淘宝 编辑:程序博客网 时间:2024/05/18 14:11

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:
97 8- -- -- -0 12 34 5- -- -
Sample Output 1:
YES 8
Sample Input 2:
8- -4 50 6- -2 3- 7- -- -
Sample Output 2:
NO 1

 

 

 

#include <stdio.h>    #include <stdlib.h>    #include <string.h>#define MAX 25typedef struct node{int left;int right;}NODE;NODE a[MAX];int flag[MAX];int main(){int N, i;int NotComplete;int left, right, root;char buffer1[MAX], buffer2[MAX];int queue[MAX], start, end;//freopen("d:\\input.txt", "r", stdin);scanf("%d", &N);NotComplete = 0;for (i = 0; i < N; i++){a[i].left = -1;a[i].right = -1;}for (i = 0; i < N; i++){scanf("%s%s", buffer1, buffer2);if (buffer1[0] == '-' && buffer2[0] == '-')//叶子节点{continue;}else{if (buffer1[0] != '-' && buffer2[0] != '-')//父节点{left = atoi(buffer1);right = atoi(buffer2);flag[left] = 1;flag[right] = 1;a[i].left = left;a[i].right = right;}else{NotComplete++;if (buffer1[0] != '-'){flag[atoi(buffer1)] = 1;a[i].left = atoi(buffer1);}if (buffer2[0] != '-'){flag[atoi(buffer2)] = 1;a[i].right = atoi(buffer2);}if (buffer1[0] == '-' && buffer2[0] != '-')//不可能完全{NotComplete = 2;break;}}}}for (i = 0; i < N; i++){if (flag[i] != 1){break;}}root = i;if (NotComplete > 1){printf("NO %d", root);return 0;}start = 0;end = 0;queue[end++] = root;while (start != end){if (a[queue[start]].left != -1){queue[end++] = a[queue[start]].left;if (NotComplete == -1)  //叶节点后出现了父节点{NotComplete = -2;}}if (a[queue[start]].right != -1){queue[end++] = a[queue[start]].right;if (NotComplete == -1)//叶节点后出现了父节点{NotComplete = -2;}}else if (a[queue[start]].right == -1 && a[queue[start]].left == -1){if (NotComplete != -2)//层序遍历一旦出现叶节点,接下来必须都是叶节点{NotComplete = -1; //记录已经出现了一个叶节点}}start++;}if (NotComplete == -2) //叶节点后出现了父节点{printf("NO %d", root);return 0;}printf("YES %d", queue[start - 1]);return 0;}


 

0 0
原创粉丝点击