二叉树(C++,代码)

该程序实现了基于前序输入创建二叉树、复制二叉树以及计算二叉树的深度、节点数、叶子节点数等功能。还提供了前序、中序和后序遍历的实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 例子:前序输入                 AB##CDF#G#E####            (#表示空,不存在)

#include<iostream>
using namespace std;
typedef struct BiNode
{
	char data;
	struct BiNode* lchild, * rchild;
}BiNode,*Bitree;
char ch;
int m, n;
typedef struct 
{
	char data[100];
	int front, rear;
}sqqueue;
bool newtree(Bitree& t)//初始化树
{
	t = new BiNode;
	return 1;
}
void createbitree(Bitree& t)//前序建树
{
	t = new BiNode;
	cin >> ch;
	if (ch == '#') t = NULL;
	else
	{
		t->data = ch;
		createbitree(t->lchild);
		createbitree(t->rchild);
	}
}
int Copy(Bitree t, Bitree &newt)//复制树
{
	if (t == NULL)
	{
		newt = NULL;
		return 0;
	}
	else
	{
		newt = new BiNode;
		newt->data = t->data;
		Copy(t->lchild, newt->lchild);
		Copy(t->rchild, newt->lchild);
	}
	return 1;
}
int Depth(Bitree t)//深度
{
	if (t == NULL) 
		return 0;
	else
	{
		m = Depth(t->lchild);
		n = Depth(t->rchild);
		if (m > n) return(m + 1);
		else return (n + 1);
	}
}
int Nodecount(Bitree t)//节点数
{
	if (t == NULL) return 0;
	else return Nodecount(t->lchild) + Nodecount(t->rchild) + 1;
}
int Leadcount(Bitree t)//叶子节点数
{
	if (t == NULL) return 0;
	if (t->lchild == NULL && t->rchild == NULL)
		return 1;
	else
		return Leadcount(t->lchild) + Leadcount(t->rchild);
}
bool pretree(Bitree t)//前序遍历
{
	if (t == NULL) return true;
	else
	{
		cout << t->data;
		pretree(t->lchild);
		pretree(t->rchild);
	}
	return 1;
}
bool intree(Bitree t)//中序遍历
{
	if (t == NULL) return true;
	else
	{
		intree(t->lchild);
		cout << t->data;
		intree(t->rchild);
	}
	return true;
}
bool posttree(Bitree t)//后序遍历
{
	if (t == NULL) return true;
	else
	{
		posttree(t->lchild);
		posttree(t->rchild);
		cout << t->data;
	}
	return 1;
}
int main()
{
	int n;
	cin >> n;
	Bitree t;
	newtree(t);
	while (n)
	{
		if (n == 1)//前序建立二叉树 #表示空
		{
			cout << "前序建立二叉树 #表示空" << endl;
			createbitree(t);
		}
		if (n == 2)//复制树
		{
			cout << "复制树" << endl;
			Bitree newt;
			Copy(t, newt);
		}
		if (n == 3)//二叉树深度
		{
			cout << "二叉树深度" << endl;
			int a = Depth(t);
			cout << a<<endl;
		}
		if (n == 4)//节点数
		{
			cout << "节点数" << endl;
			int a = Nodecount(t);
			cout << a<<endl;
		}
		if (n == 5)//叶子节点数
		{
			cout << "叶子节点数"<<endl;
			int a = Leadcount(t);
			cout << a<<endl;
		}
		if (n == 6)//前序遍历
		{
			cout << "前序遍历" << endl;
			pretree(t); 
			cout << endl;
		}
		if (n == 7)//中序遍历
		{
			cout << "中序遍历" << endl;
			intree(t);
			cout << endl;
		}
		if (n == 8)//后序遍历
		{
			cout << "后序遍历" << endl;
			posttree(t);
			cout << endl;
		}
		cout << "输入n" << endl;;
		cin >> n;
	}
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值