hhh,第一次写博客,不足之处多多建议!
C+数据结构(树)
内容:二叉树的创建(先序递归),结点数的统计,树的深度,满二叉树的判断等基本内容
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int p; //定义一个全局变量计数
typedef struct node
{//定义结点的结构体,定义BitNode 为结构体node的变量
char data;
struct node *lchild, *rchild;
} BitNode;
BitNode *createBt()
{//创建二叉树的链式存储
BitNode *bt;
char ch;
scanf("\n%c", &ch);
if(ch == '#')
bt = NULL;
else
{
bt = (BitNode *)malloc(sizeof(BitNode));
bt->data = ch;
bt->lchild = createBt();
bt->rchild = createBt();
}
return bt;
}
void PreOrder(BitNode *bt)
{//先序遍历
if(bt != NULL)
{
printf("%c", bt->data);
PreOrder(bt->lchild);
PreOrder(bt->rchild);
}
}
int treehigh(BitNode *bt)
{//求二叉树深度
int lh,rh,h;
if(bt == NULL)
{
h=0;
}
else
{
lh = treehigh(bt->lchild);
rh = treehigh(bt->rchild);
h = (lh>rh?lh:rh)+1;
}
return h;
}
int CountNode(BitNode *bt)
{//计算二叉树的总结点数
if(bt != NULL)
{
CountNode(bt->lchild);
CountNode(bt->rchild);
p++;
}
return p;
}
int judgetree(int d, int f)
{//判断该二叉树是否是满二叉树
int n;
n = pow(2,d)-1;
if(n == f)
printf("是\n");
else
printf("不是\n");
return 0;
}
int main(int argc, char *argv[]) {
BitNode *bt;
int d,f;
printf("输入二叉树\n");
bt = createBt();
d = treehigh(bt);
printf("树的深度:%d\n", d);
f = CountNode(bt);
printf("结点总数%d\n",p);
printf("是否为满二叉树:");
judgetree(d,f);//判断是否是满二叉树
return 0;
}