2024.2.7

2024.2.7_第1张图片

 

#include
#include
#include
typedef char datatype;
 
typedef struct node
{
	//数据域
	datatype data;
	//指针域:左
	struct node *lchild;
	//指针域:右
	struct node *rchild;
}*btree;
 
//创建节点
btree creat_node()
{
	btree s=(btree)malloc(sizeof(struct node));
	if(s==NULL)
		return NULL;
	s->data='\0';
	s->lchild=s->rchild=NULL;
	return s;
}
 
//创建二叉树
btree creat_tree()
{
	datatype element;
	printf("please enter element:");
	scanf(" %c",&element);
	if(element=='#')
		return NULL;
	//节点
	btree tree=creat_node();
	tree->data=element;
	//loop left
	puts("left");
	tree->lchild=creat_tree();
	//loop right
	puts("right");
	tree->rchild=creat_tree();
	return tree;
}
 
//前序遍历
void first(btree tree)
{
	if(tree==NULL)
		return;
	//遍历根
	printf("%c",tree->data);
	//左孩子遍历
	first(tree->lchild);
	//右孩子遍历
	first(tree->rchild);
}
 
//中序遍历
void mid(btree tree)
{
	if(tree==NULL)
		return;
	//左孩子遍历
	mid(tree->lchild);
	//遍历根
	printf("%c",tree->data);
	//右孩子遍历
	mid(tree->rchild);
}
//后序遍历
void last(btree tree)
{
	if(tree==NULL)
		return;
	//左孩子遍历
	last(tree->lchild);
	//右孩子遍历
	last(tree->rchild);	
	//遍历根
	printf("%c",tree->data);
}
 
//计算节点个数
void count(btree tree,int *n0,int *n1,int *n2)
{
	if(tree==NULL)
		return;
	if(!tree->lchild && !tree->rchild)
		++*n0;
	else if(tree->lchild && tree->rchild)
		++*n2;
	else 
		++*n1;
	//left loop
	count(tree->lchild,n0,n1,n2);
	//right loop
	count(tree->rchild,n0,n1,n2);
}
 
//深度计算     
int high(btree tree)
{
	if(tree==NULL)
		return 0;
	//left
	int left=1+high(tree->lchild);
	//right
	int right=1+high(tree->rchild);
 
	return left>right?left:right;
}
 
int main(int argc, const char *argv[])
{
	//创建树
	btree tree=creat_tree();
	//前序遍历
	puts("first:");
	first(tree);
	puts("");
	//中序遍历
	puts("mid:");
	mid(tree);
	puts("");
	//后序遍历
	puts("last:");
	last(tree);
	puts("");
 
	//计算节点个数
	int n0=0,n1=0,n2=0;
	count(tree,&n0,&n1,&n2);
	printf("n0=%d n1=%d n2=%d n=%d\n",n0,n1,n2,n0+n1+n2);
 
	//深度计算
	int len=high(tree);
	printf("len=%d\n",len);
 
 
	return 0;
}

 2024.2.7_第2张图片

你可能感兴趣的:(算法,数据结构)