2.7作业

2.7作业_第1张图片

程序代码:

#include
#include
#include
typedef char datatype;


//定义节点结构体
typedef struct Node
{
	datatype data;//数据域:数据元素
	struct Node *lchild;//指针域:存储左孩子的节点地址
	struct Node *rchild;//指针域:存储右孩子的节点地址
}*Btree;


//创建节点
Btree create_node()
{
	Btree s=(Btree)malloc(sizeof(struct Node));
	if(s==NULL)
		return NULL;
	s->data='\0';
	s->lchild=s->rchild=NULL;
	return s;
}

//创建二叉树
Btree create_tree()
{
	datatype element;//插入的数据域
	printf("please input element:");
	scanf(" %c",&element);
	if(element=='#')
		return NULL;
	//创建节点
	Btree tree=create_node();
	tree->data=element;
	//递归实现循环创建左孩子
	tree->lchild=create_tree();
	//递归实现循环创建右孩子
	tree->rchild=create_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;
	Count(tree->lchild,n0,n1,n2);
	Count(tree->rchild,n0,n1,n2);
}

//计算深度
int high(Btree tree)
{
	if(tree==NULL)
		return 0;
	//递归计算左子树深度
	int left=1+high(tree->lchild);
	//递归计算右子树深度
	int right=1+high(tree->rchild);
	return left>right?left:right;
}
int main(int argc, const char *argv[])
{
	Btree tree=create_tree();

	first(tree);
	puts("");

	mid(tree);
	puts("");

	last(tree);
	puts("");


	int n0=0,n1=0,n2=0;
	Count(tree,&n0,&n1,&n2);
	int len=high(tree);
	printf("n0=%d,n1=%d,n2=%d,n=%d,len=%d\n",n0,n1,n2,n0+n1+n2,len);
	return 0;
}

运行结果:

2.7作业_第2张图片

你可能感兴趣的:(c语言,算法,开发语言)