树的应用-树的叶子结点数、树的深度、树的拷贝

// 树的遍历.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<stdlib.h>
//二叉链表示法  
typedef struct BiTNode
{
	int data;
	BiTNode *lchild, *rchild;
};
typedef struct BiTNode* Bitree;
//先序遍历
void PreOder(BiTNode *root)
{
	if (root==NULL)
	{
		return;
	}
	printf("%d ",root->data);
	//遍历左子树
	PreOder(root->lchild);
	//遍历右子树
	PreOder(root->rchild);

}
//中序遍历
void InOrder(BiTNode *root)
{
	if (root == NULL)
	{
		return;
	}

	//遍历左子树
	InOrder(root->lchild);
	printf("%d ", root->data);
	//遍历右子树
	InOrder(root->rchild);
}
//后序遍历
void PostOrder(BiTNode *root)
{
	if (root == NULL)
	{
		return;
	}

	//遍历左子树
	PostOrder(root->lchild);
	
	//遍历右子树
	PostOrder(root->rchild);
	printf("%d ", root->data);
}

//计算二叉树中叶子结点的数目
int num = 0;
void LeafCount(BiTNode *root)
{
	if (root!=NULL)
	{
		if (root->lchild ==NULL&&root->rchild==NULL)
		{
			num++;
			printf("%d\n",root->data);
		}
		LeafCount(root->lchild);
		LeafCount(root->rchild);
	}
	//return 0;
	//printf("%d\n  ", num);
}
//计算二叉树的深度
int DepthTree(BiTNode *root)
{
	int leftDepth = 0;
	int rightDepth = 0;
	int depth = 0;
	if (root==NULL)
	{
		depth = 0;
		return depth;
	}
	//求左子树高度
	leftDepth = DepthTree(root->lchild);
	//求右子树高度
	rightDepth = DepthTree(root->rchild);
	//+1
	depth = 1+(leftDepth > rightDepth ? leftDepth : rightDepth);
	return depth;
}
//copy二叉树
BiTNode* CopyTree(BiTNode* root)
{
	BiTNode* newNode;
	BiTNode* newLeftNode;
	BiTNode* newRightNode;
	if (root==NULL)
	{
		return NULL;
	}
	if (root->lchild!=NULL)
	{
		newLeftNode = CopyTree(root->lchild);
	}
	else
	{
		newLeftNode = NULL;
	}
	if (root->rchild != NULL)
	{
		newRightNode = CopyTree(root->rchild);
	}
	else
	{
		newRightNode = NULL;
	}
	newNode = (BiTNode*)malloc(sizeof(BiTNode));
	if (newNode == NULL)
	{
		return NULL;
	}
	newNode->lchild = newLeftNode;
	newNode->rchild = newRightNode;
	newNode->data = root->data;
	return newNode;
}

int main()
{
		BiTNode t1, t2, t3, t4, t5;
		memset(&t1,0,sizeof(BiTNode));
		memset(&t2, 0, sizeof(BiTNode));
		memset(&t3, 0, sizeof(BiTNode));
		memset(&t4, 0, sizeof(BiTNode));
		memset(&t5, 0, sizeof(BiTNode));
		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;
		PreOder(&t1);
		printf("\npre\n");
		InOrder(&t1);
		printf("\nin\n");
		PostOrder(&t1);
		printf("\npost\n");
		//system("pause");
		LeafCount(&t1);
		printf("叶子结点个数 %d\n",num);
		printf("树的高度: %d\n", DepthTree(&t1));

		BiTNode* root = CopyTree(&t1);
		PreOder(root);
		printf("\npre\n");
		system("pause");
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值