1110 Complete Binary Tree (25分)
作者:CHEN, Yue
单位:浙江大学
代码长度限制:16 KB
时间限制:400 ms
内存限制:64 MB
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
题意:
给一颗二叉树,要求判断是否是完全二叉树,若是求出最后一个结点的下标。若不是写出这棵二叉树的根结点。
思路:
首先将结点孩子转换为整数下标,空节点设为-1,树种没有出现过的孩子结点就是根结点(理解:谁的孩子都不是,肯定是爸爸)。完全二叉树在结点(1-N)从上到下从左至右的情况下序列号满足,左孩子结点序号为父节点的2倍,右孩子结点序号为父节点的2倍+1。所用用深度优先去按照完全二叉树的定义去给这棵树定序号,若最大序号数等于结点个数,那么就是完全二叉树,否则不是。
参考代码:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct Node {
int left, right;
} node[20];
int n, root, maxindex = 0, maxid;
void dfs(int rt, int index) {
if (index > maxindex) {
maxindex = index;
maxid = rt;
}
if (node[rt].left != -1)dfs(node[rt].left, index * 2);
if (node[rt].right != -1)dfs(node[rt].right, index * 2 + 1);
}
int main() {
string s1, s2;
scanf("%d", &n);
vector<int> hashtable(n, 0);
for (int i = 0; i < n; i++) {
cin >> s1 >> s2;
node[i].left = isdigit(s1[0]) ? stoi(s1) : -1;
node[i].right = isdigit(s2[0]) ? stoi(s2) : -1;
if (node[i].left >= 0)hashtable[node[i].left] = 1;
if (node[i].right >= 0)hashtable[node[i].right] = 1;
}
for (root = 0; root < n && hashtable[root] != 0; root++);
dfs(root, 1);
if (maxindex == n)printf("YES %d", maxid);
else printf("NO %d", root);
return 0;
}
如有错误,欢迎指正