1110 Complete Binary Tree (25point(s))
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:
9
7 8
- -
- -
- -
0 1
2 3
4 5
- -
- -
Sample Output:
YES 8
Sample Input:
8
- -
4 5
0 6
- -
2 3
- 7
- -
- -
Sample Output:
NO 1
题目大意:
输入 N 个节点,依次给出 N 个节点的左右孩子
输出判断是否是完全二叉树,和最后一个节点号
设计思路:
完全二叉树,最大的下标值一定等于最大的节点数
- 用数组存储二叉树
- 利用父节点的左右孩子 2 倍和 2 倍加 1,递归出最大的下标值
编译器:C (gcc)
#include <stdio.h>
#include <stdlib.h>
int tree[20][2];
int imax = 0, ilast = 0;
void dfs(int root, int index)
{
if (imax < index) {
imax = index;
ilast = root;
}
if (tree[root][0] != -1)
dfs(tree[root][0], index * 2);
if (tree[root][1] != -1)
dfs(tree[root][1], index * 2 + 1);
}
int main(void)
{
int n;
int i, root = 0, child[20] = {0};
char a[3], b[3];
scanf("%d", &n);
for (i = 0; i < n; i++) {
scanf("%s %s", a, b);
if (a[0] != '-') {
tree[i][0] = atoi(a);
child[atoi(a)] = 1;
} else {
tree[i][0] = -1;
}
if (b[0] != '-') {
tree[i][1] = atoi(b);
child[atoi(b)] = 1;
} else {
tree[i][1] = -1;
}
}
while (child[root] == 1)
root++;
dfs(root, 1);
if (imax == n)
printf("%s %d", "YES", ilast);
else
printf("%s %d", "NO", root);
return 0;
}