数据结构-求叶子节点个数,树的高度,拷贝二叉树03

求叶子节点个数,树的高度,拷贝二叉树


/*
	   1
	2     3
4       5
	*/
typedef struct BiTNode
{
	int data;
	struct BiTNode *lchild, *rchild; //左孩子 右孩子
}BiTNode, *BiTree;
void PreOrder(BiTNode *T)
{
	if (T != NULL)
	{
		printf("%d ", T->data);
		PreOrder(T->lchild);
		PreOrder(T->rchild);
	}
}

void InOrder(BiTNode *T)
{
	if (T != NULL)
	{
		InOrder(T->lchild);
		printf("%d ", T->data);
		InOrder(T->rchild);
	}
}

void PostOrder(BiTNode *T)
{
	if (T != NULL)
	{
		PostOrder(T->lchild);
		PostOrder(T->rchild);
		printf("%d ", T->data);
	}
}

//求二叉树的叶子节点个数:左右节点都为空的
void GetLeafCount(BiTNode *T,int *count)
{
	if (T != NULL)
	{
		if (T->lchild == NULL &&T->rchild == NULL)
		{
			(*count)++;
		}
		GetLeafCount(T->lchild, count);
		GetLeafCount(T->rchild, count);
	}
}

//求二叉树的高度(深度)(几层):
//也是递归求解,左右子树的高度中的比较高的加上根节点就是树的高度
int GetDepth(BiTNode *T)
{
	int ndepth = 0, ldepth = 0, rdepth = 0;
	if (!T)
	{		
		return 0;
	}

	ldepth = GetDepth(T->lchild);
	rdepth = GetDepth(T->rchild);
	ndepth = 1 + (ldepth > rdepth ? ldepth : rdepth);
	return ndepth;
}
//拷贝二叉树
BiTNode * copyTree(BiTNode *T)
{

	if (!T)
	{
		return NULL;
	}
	BiTNode *newbit = NULL, *lptr = NULL, *rptr = NULL;

	if (T->lchild)
	{
		lptr = copyTree(T->lchild);
	}
	else
	{
		lptr = NULL;
	}

	if (T->rchild)
	{
		rptr = copyTree(T->rchild);
	}
	else
	{
		rptr = NULL;
	}
	newbit = (BiTNode *)malloc(sizeof(BiTNode));
	newbit->lchild = lptr;
	newbit->rchild = rptr;
	newbit->data = T->data;
	return newbit;

}

void main()
{

	BiTNode b1, b2, b3, b4, b5;
	memset(&b1, 0, sizeof(BiTNode));
	memset(&b2, 0, sizeof(BiTNode));
	memset(&b3, 0, sizeof(BiTNode));
	memset(&b4, 0, sizeof(BiTNode));
	memset(&b5, 0, sizeof(BiTNode));
	b1.data = 1;
	b2.data = 2;
	b3.data = 3;
	b4.data = 4;
	b5.data = 5;
	


	//构建树关系
	b1.lchild = &b2;
	b1.rchild = &b3;
	b2.lchild = &b4;
	b3.lchild = &b5;
	printf("\n先根遍历");
	PreOrder(&b1);
	printf("\n中根遍历");
	InOrder(&b1);

	printf("\n后根遍历");
	PostOrder(&b1);
	cout << endl;
	int ncount = 0;
	GetLeafCount(&b1, &ncount);
	cout << ncount << endl;

	cout << "深度:" << GetDepth(&b1) << endl;

	printf("\n中根遍历");
	BiTNode *T2 = copyTree(&b1);
	InOrder(T2);
	system("pause");
}

结果;
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

发如雪-ty

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

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

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

打赏作者

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

抵扣说明:

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

余额充值