树的简单遍历、深度、叶子数量、拷贝

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct BiNode
{
	int data;
	struct BiNode *lchild, *rchild;
}BiNode,*BiTree;


//先序遍历
void preOrder(BiNode *root)
{
	if (root != NULL)
	{
		printf("%d",root->data);
		preOrder(root->lchild);
		preOrder(root->rchild);
	}
}

//中序遍历
void inOrder(BiNode *root)
{
	if (root != NULL)
	{
		inOrder(root->lchild);
		printf("%d", root->data);
		inOrder(root->rchild);
	}
}

//后序遍历
void postOrder(BiNode *root)
{
	if (root != NULL)
	{
		postOrder(root->lchild);
		postOrder(root->rchild);
		printf("%d", root->data);
	}
}

//计算叶子结点
void CountLeafNum(BiNode *root, int *num)
{
	if (root != NULL)
	{
		if (!root->lchild&&!root->rchild)
		{
			(*num)++;
			printf("%d", root->data);
		}
		CountLeafNum(root->lchild,num);
		CountLeafNum(root->rchild,num);
	}
}

//计算深度
int GetDepth(BiNode *root)
{
	int ldepth = 0, rdepth = 0;
	int depthVal = 0;

	if (root == NULL)
	{
		return depthVal;
	}

	ldepth = GetDepth(root->lchild);//求出左子树深度
	rdepth = GetDepth(root->rchild);//求出右子树深度

	depthVal = 1 + ((ldepth > rdepth) ? ldepth : rdepth);//左右子树最大深度 + 1 即为树的最大深度。
	return depthVal;
}

//拷贝树
BiNode *Copy_tree(BiNode *root)
{
	BiNode *tmp = NULL;
	if (root != NULL)
	{
		tmp = (BiNode *)malloc(sizeof(BiNode));
		tmp->data = root->data;
		tmp->lchild = Copy_tree(root->lchild);
		tmp->rchild = Copy_tree(root->rchild);
	}
	return tmp;
}

void main01()
{
	BiNode t1, t2, t3, t4, t5;
	memset(&t1, 0, sizeof(BiNode));
	memset(&t2, 0, sizeof(BiNode));
	memset(&t3, 0, sizeof(BiNode));
	memset(&t4, 0, sizeof(BiNode));
	memset(&t5, 0, sizeof(BiNode));
	t1.data = 1;
	t2.data = 2;
	t3.data = 3;
	t4.data = 4;
	t5.data = 5;
	t1.lchild = &t2;
	t1.rchild = &t3;

	t2.lchild = &t4;
	t3.lchild = &t5;

	preOrder(&t1);
	inOrder(&t1);
	postOrder(&t1);
}

void main()
{
	int num = 0;
	BiTree p1, p2, p3, p4, p5;
	p1 = (BiTree)malloc(sizeof(BiNode));
	p2 = (BiTree)malloc(sizeof(BiNode));
	p3 = (BiTree)malloc(sizeof(BiNode));
	p4 = (BiTree)malloc(sizeof(BiNode));
	p5 = (BiTree)malloc(sizeof(BiNode));

	memset(p1, 0, sizeof(BiNode));
	memset(p2, 0, sizeof(BiNode));
	memset(p3, 0, sizeof(BiNode));
	memset(p4, 0, sizeof(BiNode));
	memset(p5, 0, sizeof(BiNode));

	p1->data = 1;
	p2->data = 2;
	p3->data = 3;
	p4->data = 4;
	p5->data = 5;

	p1->lchild = p2;
	p1->rchild = p3;

	p2->lchild = p4;

	p3->lchild = p5;

	preOrder(p1);
	inOrder(p1);
	postOrder(p1);

	CountLeafNum(p1, &num);
	printf("num:%d", num);

	printf("树的高度为:%d", GetDepth(p1));

	preOrder(Copy_tree(p1));
	inOrder(Copy_tree(p1));
	postOrder(Copy_tree(p1));
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值