二叉树的基本操作

实验完整代码  

#include<stdio.h>
#include<malloc.h>

//二叉树
typedef char datatype;
typedef struct BiTNode{
	datatype data;
	BiTNode *lchild,*rchild;
}BiTree; 

//先序遍历构建二叉树 
BiTree *CreateTree(BiTree *bt){
	char x;
//	printf("请以先序输入树的所有结点值:\n");//输入AB##C##,每次递归读入缓存区一个字符 
	scanf("%c",&x);
	if(x=='#'){
		bt=NULL; 
	}
	else{
		bt=(BiTree *)malloc(sizeof(BiTree));
		bt->data=x;
		bt->lchild=CreateTree(bt->lchild);//递归调用先序建树 
		bt->rchild=CreateTree(bt->rchild);
	}
	return bt;
}

//先序遍历
void PreOrder(BiTree *bt){
	if(bt!=NULL){
		printf("%c ",bt->data);
		PreOrder(bt->lchild);
		PreOrder(bt->rchild);
	}
} 

//中序遍历
void InOrder(BiTree *bt){
	if(bt!=NULL){
		InOrder(bt->lchild);
		printf("%c ",bt->data);
		InOrder(bt->rchild);
	}
} 

//后序遍历
void PostOrder(BiTree *bt){
	if(bt!=NULL){
		PostOrder(bt->lchild);
		PostOrder(bt->rchild);
		printf("%c ",bt->data);
	}
} 

//求二叉树叶子结点数 
void CountLeaf(BiTree *bt,int *x){
	if(bt!=NULL){
		if(bt->lchild==NULL && bt->rchild==NULL){
			(*x)++;
		}
		CountLeaf(bt->lchild,x);
		CountLeaf(bt->rchild,x); 
	} 
}

//求二叉树深度
int Depth(BiTree *bt){
	int ldepth,rdepth,maxdepth;
	if(bt==NULL){
		return 0;
	}
	ldepth=Depth(bt->lchild);
	rdepth=Depth(bt->rchild);
	maxdepth=ldepth>rdepth?ldepth+1:rdepth+1;
	return maxdepth;
} 

//测试
int main(){
	BiTree *t;
	int x;
	int depth; 
	
	printf("请以先序输入树的所有结点值:\n");
	t=CreateTree(t);//初始化建树 
	
	//先序遍历
	printf("先序遍历结果为:\n");
	PreOrder(t);
	printf("\n");
	
	
	printf("中序遍历结果为:\n");
	InOrder(t);
	printf("\n");
	
	
	printf("后续遍历结果为\n");
	PostOrder(t);
	printf("\n");
	
	CountLeaf(t,&x);
	printf("二叉树叶子节点数为:%d\n",x);
	
	depth=Depth(t);
	printf("二叉树的深度为:%d\n",depth);
} 

实验结果

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值