判断满二叉树
程序员文章站
2022-03-14 19:22:08
...
/*
判断二叉树是否是满二叉树
思路:满二叉树的叶子结点数=2的(n-1)次方,n代表树的高度(一个结点表示树的高度为1)
*/
#include <iostream>
#include <cstdlib>
#include <cmath>
using namespace std;
typedef char ElemType;
typedef struct BiTNode{
ElemType data;
struct BiTNode *lchild, *rchild;
}*BiTree;
void CreateTree(BiTree &t){
ElemType e;
cin >> e;
if(e=='#')
t = NULL;
else{
t = (BiTree)malloc(sizeof(BiTNode));
t->data = e;
CreateTree(t->lchild);
CreateTree(t->rchild);
}
}
void Countleaves(BiTree T, int &count){
if(T){
if(!T->lchild && !T->rchild) //叶子结点
count++;
Countleaves(T->lchild, count);
Countleaves(T->rchild, count);
}
}
int getDepth(BiTree t){
int lchildDepth, rchildDepth;
if(!t) return 0; //空树的高度为0
else{
lchildDepth = getDepth(t->lchild);
rchildDepth = getDepth(t->rchild);
return (lchildDepth>rchildDepth) ? (lchildDepth+1) : (rchildDepth+1);
}
}
bool isFullTree(BiTree t) {
int leaves;
Countleaves(t, leaves);
// cout << leaves << " " << getDepth(t) << endl;
if(t==NULL){
return false;
}else if(int(pow(2, getDepth(t)-1)) == leaves){
return true;
}else{
return false;
}
}
int main(){
BiTree t;
int count;
cout << "输入二叉树(先序、空树用#表示):";
CreateTree(t);
if(isFullTree(t)){
cout << "该树是满二叉树" << endl;
}else{
cout << "该树不是满二叉树" << endl;
}
return 0;
}
程序小白,如果代码中有任何问题,欢迎指出。