1043. 完全二叉树
Description
给出一棵二叉树,判断其是否为完全二叉树。
Input Format
第一行,N<1000000,表示二叉树节点数。
默认序号为0的节点为树根。接下来共N-1行,依次表示序号为1,...,N-1的节点的父亲节点序号。
如果一个节点有两个孩子节点,左孩子节点序号总是小于右孩子节点序号。
Output Format
仅一行,如果是完全二叉树,则输出true,否则输出false。
Hint
Sample Input1
6
0
1
1
0
4
Sample Output1
true
Sample Input2
6
0
1
1
0
3
Sample Output2
false
思路:用结构体存储结点信息,因为是完全二叉树,所以根据完全二叉树的性质,n为结点数,深度K=(log2(n)向下取整)+1;
叶子结点数(无左右孩子的结点) =n+1-Pow(2,k-1);
代码如下:
#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std;
int cnt1=1,cnt2=1,n;
struct Tree
{
int Lchild;
int Rchild;
};
Tree a[1000000];
void Treedef()//初始化树
{
for(int i=0;i<100000;i++)
{
a[i].Lchild=0;
a[i].Rchild=0;
}
}
int find1(int x)//因为左结点序号小于右结点
{
for(int i=x;i<a[0].Rchild;i++)
{
if(a[i].Lchild!=0 || a[i].Rchild!=0)
{
cnt1++;
}
}
return cnt1+1;
}
int find2(int y)
{
for(int i=y;i<n;i++)
{
if(a[i].Lchild!=0 || a[i].Rchild!=0)
{
cnt2++;
}
}
return cnt2+1;
}
int cmp(int a,int b)//找出最大子深度
{
if(a>b)
{
return a;
}
if(a<b)
{
return b;
}
if(a==b)
{
return a;
}
}
int main()
{
Treedef();
int m,num=1,cnt=0;
cin>>n;
for(int i=0;i<n-1;i++)
{
cin>>m;
if(a[m].Lchild!=0)
{
a[m].Rchild=num++;
}
else
{
a[m].Lchild=num++;
}
}
int k=log10(n)/log10(2)+1;//计算树的深度
int mac=cmp(find1(a[0].Lchild),find2(a[0].Rchild));//找出左右子树的最大深度
for(int i=0;i<n;i++)//统计叶子结点数
{
if(a[i].Lchild==0&&a[i].Rchild==0)
{
cnt++;
}
}
if(cnt==(n+1-pow(2,k-1)) &&mac-1==k)//判断是否为完全二叉树
{
cout<<"true";
}
else
{
cout<<"false";
}
return 0;
}
虽然AC了,但是代码不够好;有好想法的朋友欢迎探讨!!!;
有需要可以关注微信公众号:算法那些事儿;