二叉树的创建与基本操作

二叉树的性质我就不多说了,毕竟是笔记,直接上一点干货(代码操作)

  • 根据二叉树的性质,建立一个二叉树存储结构。
typedef char DataType;
/*二叉树存储结构类型*/ 
typedef struct tonde{
	DataType data;
	struct tonde *lchile,*rchile;//左孩子,右孩子指针
}BT; 
  • 创建一个二叉树,按二叉树带空指针的先序依次输入(解释:因为在创建时我要从根结点开始建立,并且返回这个树根结点,“树高万丈不忘根,人若辉煌不忘本嘛”);

输入:AB0D00CE00F00,“0代表空节点”

注:自己在小本本上演示一下这个代码的递归过程,有利于理解递归这个神奇的的算法。

/*二叉树建立算法描述*/
BT* CreatBTree(){
	BT* root;
	char ch;
	scanf("%c",&ch);
	getchar();//吃掉回车键,防止代码出错,是一个字符输入时比较容易出错的地方
	if(ch == '0'){
		root = NULL;
	}else{
		root = (BT*)malloc(sizeof(BT));
		root->data = ch;
		printf("请输入%c的左孩子结点:",root->data);
		root->lchile = CreatBTree();//递归建立新的结点
		printf("请输入%c的右孩子结点:",root->data);
		root->rchile = CreatBTree();
	}
	return root;
}
  • 二叉树的遍历以及记录总结点数和统计叶子结点数
int count=0;//叶子结点数 
int count_1=0;//二叉树总结点数 
void All_Order_Num(BT* root){
	if(root == NULL){
		return;
	}else{
		count_1++;//只要结点不为空我就计算一次 
		printf("%c",root->data);
		/*统计二叉树叶子结点的个数,在左右子树都为空的话统计*/
		if(root->lchile == NULL && root->rchile == NULL){
			count++;
		}
		All_Order_Num(root->lchile);
		All_Order_Num(root->rchile);	
	}
}

这就是将三个功能放在一起了,但是要注意到把这三个功能分开写和放到一起的递归的形式是一样的,所以才能这样写一下,我老师第一次这样出题,我没反应过来,(ps:没好好看书噻)

  • 求二叉树的深度
    递归统计左子树的深度和右子树深度,递归结束时返回其中最大的一个,即是二叉树的深度。
int TreeDepth(BT *root){
	
	int ldep,rdep;/*求二叉树深度*/
	if(root == NULL){
		return 0;
	}else{
		ldep = TreeDepth(root->lchile);
		rdep = TreeDepth(root->rchile);
	}
	if(ldep>rdep){
		return ldep+1;
	}else{
		return rdep+1;
	}	 
}

分开写的几个遍历和统计算法描述:

/*三种输出*/
void PreOrder(BT* root){
	if(root == NULL){
		return;
	}else{
		printf("%c",root->data);
		PreOrder(root->lchile);
		PreOrder(root->rchile);
	}
}
void InOeder(BT* root){
	if(root == NULL){
		return;
	}else{
		InOeder(root->lchile);
		printf("%c",root->data);
		InOeder(root->lchile);	
	}
}
void PostOrder(BT* root){
	if(root == NULL){
		return;
	}else{
		InOeder(root->lchile);
		InOeder(root->lchile);	
		printf("%c",root->data);
	}
}

统计二叉树叶子结点和二叉树总结点

int count=0;
void Leafnum(BT* root){
	if(root){/*统计二叉树叶子结点的个数,在左右子树都为空的话*/
		if(root->lchile == NULL && root->rchile == NULL){
			count++;
		}
		Leafnum(root->lchile);
		Leafnum(root->rchile);
	}
}

void leafsum(BT* root){
	if(root){/*求二叉树结点总数*/
		count++;
		leafsum(root->lchile);
		leafsum(root->rchile);
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

勇敢*牛牛

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值