数据结构

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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值