判断二叉树是否满二叉树和完全二叉树(二叉树用二叉链的形式存储)
思路
1满二叉树必须满足每层节点数为2的(n - 1)次方
2若不为完全二叉树只有当某节点左儿子为空,右儿子不为空,或者叶子节点不在同一层
代码
#include "bits/stdc++.h"
using namespace std;
struct node
{
char data;
struct node *lc;
struct node *rh;
};
int find(char s[], int len)
{
int match = 0;
int i;
for(i = 0; i < len; i++)
{
if(s[i] == '(')
++match;
else if(s[i] == ')')
--match;
if(match==0 && s[i]==',')
break;
}
return i;
}
node *creat(char s[], int len) //建树
{
node *root = (node *)malloc(sizeof(node));
root->data = s[0];
if(len == 1)
{
root->lc = NULL;
root->rh = NULL;
}
else
{
int com = find(s + 2, len - 2);
root->lc = creat(s + 2, com);
root->rh = creat(s + 2 + com + 1, len - 3 - com - 1);
}
return root;
}
int sum[100];
int ff = 0;
int mi = -1;
void dfs(int id, node *root)
{
int k = 0;
sum[id]++;
if(root->lc != NULL)
{
dfs(id + 1, root->lc);
}
else
{
k = 1;
if(mi == -1)
mi = id;
else
{
if(mi != id)
ff = 1;
}
}
if(root->rh != NULL)
{
dfs(id + 1, root->rh);
if(k)
{
ff = 1; //如果左节点为空那么 右节点有值不是完全二叉
}
}
else
{
if(mi == -1)
mi = id;
else
{
if(mi != id)
ff = 1;
}
}
}
int main()
{
char a[1000];
cin >> a;
node *root;
root = (node *)malloc(sizeof(node));
root = creat(a, strlen(a));
dfs(1, root);
int num = 1;
int f = 0;
cout << "这颗树的每一层的节点数为: ";
for (int i = 1; ;i++)
{
if(sum[i] == 0)
break;
cout << sum[i] << " ";
if(sum[i] != num)
{
f = 1;
break;
}
num *= 2;
}
cout << endl;
if (f)
cout << "不是满二叉树" << endl;
else
cout << "是一颗满二叉树" << endl;
if(ff)
cout << "不是完全二叉树" << endl;
else
cout << "是一颗完全二叉树" << endl;
}
运行结果