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 (≤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
解题思路:
本题考察点是判断完全二叉树。题主在调试代码时,有三个三测试点因为相同原因不能通过。节点的id可以是两位数。
补充函数:int stoi (const string& str, size_t idx = 0, int base = 10);*
Convert string to integer
判断完全二叉树(Complete Binary Tree)
若节点的左子树为空,则将节点的left设为-1,(有别于节点的编号),右子树同理,然后采用dfs算法(层序遍历),当遇到左(右子树)为空时,判断当前访问的节点数是否为n,若不为n则此树不是完全二叉树
判断满二叉树(Full Binary Tree)
与判断完全二叉树同理,判断总结点数是否是n(=2level-1),其中level是树的深度。
#include <iostream>
#include <queue>
using namespace std;
const int maxn=200;
int left1[maxn],right1[maxn];
bool exist[maxn];
int main()
{
int n;
cin>>n;
for(int i=0; i<n; i++) {
string x1,x2;
cin>>x1>>x2;
if(x1=="-") left1[i]=-1;
else {
left1[i]=stoi(x1);
exist[left1[i]]=true;
}
if(x2=="-") right1[i]=-1;
else {
right1[i]=stoi(x2);
exist[right1[i]]=true;
}
}
int root=0;
while(root<n&&exist[root]) root++;
int cnt=0;
queue<int> q;
q.push(root);
bool ans=true;
int lastnode=0;
while(!q.empty()){
int t=q.front();
q.pop();
if(t!=-1) {
cnt++;
lastnode=t;
}
else{
if(cnt!=n){
cout<<"NO " <<root<<endl;
}else
cout<<"YES "<<lastnode<<endl;
return 0;
}
q.push(left1[t]);
q.push(right1[t]);
}
return 0;
}










网友评论