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
题意:有n个点,有n行输入,从0到n,表示每个点的左右子节点,如果是“-”表示没有左结点或者右结点,如果是完全二叉树,就输出最后的节点的值,如果不是完全二叉树,就输出根节点
解题思路:根据完全二叉树的性质,我们知道最后一个节点下标跟节点个数相同(下标从1开始),所以我们对二叉树遍历,如果最后一个下标等于节点个数就是完全二叉树,如果是棵二叉树,那么最后一个节点的下标会大于节点个数(同样的结点数,但是前面有位置是空的话)我们根据这个性质来解这题。用结构体存储点的左右孩子,如果没有就赋值-1,并且对每个左右节点在Exit赋值为true,表示它是子节点(为了确定根节点,根节点不是孩子节点,所以根节点在Exit中肯定是false),我们对输入数据处理完,接下来就开始判断了,通过dfs,对左右子树递归,一旦index大于maxn,就将maxn更新,ans(答案)更新当前根节点,就一直这样子递归。
#include<iostream>
#include<cstdio>
#include<string>
using namespace std;
struct Binary{
int l,r;
};
Binary tree[100];
bool Exit[100]={false};
int maxn=-1,ans;
void dfs(int root,int index){
if(index>maxn)
{
maxn=index;
ans=root;
}
if(tree[root].l!=-1) dfs(tree[root].l,2*index);
if(tree[root].r!=-1) dfs(tree[root].r,2*index+1);
}
int main(void)
{
int n,root=0,index=1;
scanf("%d",&n);
for(int i=0;i<n;i++)
{
string l,r;
cin>>l>>r;
if(l=="-") tree[i].l=-1;
else{
tree[i].l=stoi(l);
Exit[tree[i].l]=true;
}
if(r=="-") tree[i].r=-1;
else {
tree[i].r=stoi(r);
Exit[tree[i].r]=true;
}
}
while(Exit[root]!=false) root++;
dfs(root,index);
// cout<<maxn<<endl;
if(maxn==n)
printf("%s %d\n","YES",ans);
else
printf("%s %d\n","NO",root);
return 0;
}