数据结构——二叉树的其他算法(复制、求深度、求结点数等)

1.完整代码

#include<iostream>
#include<malloc.h> 
using namespace std;

#define TElemType int
#define TRUE    1
#define FALSE   0
#define OK      1
#define ERROR   0
#define OVERFLOW -2

typedef struct BiTNode{
	TElemType data;
	struct BiTNode *lchild, *rchild;
}BiTNode, *BiTree;

/****************基本操作函数 ****************/ 
//先序创建二叉树 
int CreateBiTree(BiTree &T)
{
	TElemType a; 
	scanf("%d", &a);
	if ( 0 == a )		//输入结点的值为空 
	{
		T = NULL;		//结点为空 
	}
	else
	{
		T = (BiTree)malloc(sizeof(BiTNode));		//生成根结点 
		if ( !T )
			exit(OVERFLOW);
		T->data = a;			//将值赋给T所指结点 
		CreateBiTree(T->lchild);	//递归构造左子树 
		CreateBiTree(T->rchild);	//递归构造右子树			
	}
	return OK;
}

//先序遍历
void PreOrderTraverse(BiTree T)
{
	if ( T != NULL )
	{
		printf("%d ", T->data);			//先访问根结点 
		PreOrderTraverse(T->lchild);	//递归遍历左子树 
		PreOrderTraverse(T->rchild);	//递归遍历右子树
	}
 } 
 
//复制二叉树
//算法思想:1.如果是空数,递归结束
//		  2.否则,申请新结点空间,复制根结点 
int Copy(BiTree T, BiTree &NewT)
{
	if ( T == NULL )
	{
		NewT = NULL;
		return ERROR;
	}
	else
	{
		NewT = new BiTNode;
		NewT->data = T->data;
		Copy(T->lchild, NewT->lchild);
		Copy(T->rchild, NewT->rchild); 
	}
	return OK;
}

//计算二叉树深度
//算法思想:
//1.如果是空树,则深度为0;
//2.否则,递归计算左子树深度记为m,递归计算右子树的深度记为n,二叉树的深度为m与n的较大者加1 
int Depth(BiTree T)
{
	int m, n;
	if ( T == NULL )
		return ERROR;
	else
	{
		m = Depth(T->lchild);
		n = Depth(T->rchild);
		if ( m > n )
			return (m+1);
		else 
			return (n+1);
	}
}

//计算二叉树的结点总数
//算法思想:
//1.如果是空树,则结点个数为0;
//2.否则结点个数为左子树结点个数+右子树结点个数+1(根结点个数)。 
int NodeCount(BiTree T)
{
	if ( T == NULL )
		return ERROR;
	else
		return NodeCount(T->lchild) + NodeCount(T->rchild) + 1;
}

//计算二叉树的叶子结点数
//算法思想:
//1.如果是空树,则叶子结点个数为0;
//2.否则,为左子树叶子结点个数+右子树叶子结点个数 
int LeafCount(BiTree T)
{
	if ( T == NULL )
		return 0;
	if ( T->lchild == NULL && T->rchild == NULL )
		return 1;
	else
		return LeafCount(T->lchild) + LeafCount(T->rchild);
}

/****************主函数 ****************/ 
int main()
{
	BiTree T = NULL;
	BiTree newT = NULL;
	cout << "请按照先序遍历输入二叉树('0'无): ";
	CreateBiTree(T);
	Copy(T, newT);
	cout << "先序遍历原二叉树: "; 
	PreOrderTraverse(T);
	cout << "\n";
	
	cout << "先序遍历复制的二叉树: "; 
	PreOrderTraverse(newT);
	cout << "\n";
	
	cout << "二叉树的深度为: "; 
	cout << Depth(T) << endl;
	
	cout << "二叉树的结点总数为: "; 
	cout << NodeCount(T) << endl;
	
	cout << "二叉树的叶子结点总数为: "; 
	cout << LeafCount(T) << endl;	
	
	return 0;
}

2.测试结果

在这里插入图片描述

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值