二叉树

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
using namespace std;
typedef struct BiTNode{
	char data;
	struct BiTNode *lchild, *rchild;
}BiTNode,*BiTree;

int Max(int x, int y)
{
	return x > y ? x : y;
}

//先序建立一棵二叉树
void Create(BiTree &T)
{
	char ch;
	scanf("%c", &ch);
	if (ch == '#') T = NULL;	//T是指的是节点不是单单指树
	else
	{
		T = (BiTNode *)malloc(sizeof(BiTNode));
		T->data = ch;
		Create(T->lchild);
		Create(T->rchild);
	}
}
//先序遍历打印二叉树
void Preorder(BiTree &root)
{
	if (root != NULL)
	{
		printf("%c", root->data);		//先序把打印放前边
		Preorder(root->lchild);
		Preorder(root->rchild);
	}
}
//中序遍历打印二叉树
void Inorder(BiTree &root)
{
	if (root != NULL)
	{
		Inorder(root->lchild);
		printf("%c", root->data);		//中序把打印放中间
		Inorder(root->rchild);
	}
}

//后续遍历打印二叉树
void Postorder(BiTree &root)
{
	if (root != NULL)
	{
		Postorder(root->lchild);
		Postorder(root->rchild);
		printf("%c", root->data);	//后续就把打印放最后
	}
}
//先序遍历输出叶子结点
void Preorderleaf(BiTree &root)
{
	if (root != NULL)
	{
		if (root->lchild == NULL&&root->rchild == NULL)	//判断是否是叶子
			printf("%c", root->data);
		Preorderleaf(root->lchild);
		Preorderleaf(root->rchild);
	}
}
//统计叶子节点的个数
int LeafCount(BiTree &root)
{
	int leaf;
	if (root == NULL)	//树空
		leaf = 0;
	else if (root->lchild == NULL&&root->rchild == NULL)	//只有根节点
		leaf = 1;
	else
		leaf = LeafCount(root->lchild) + LeafCount(root->rchild);	//左右子树都不为空
	return leaf;
}
//统计树的高度
int BiTreeDepth(BiTree &root)
{
	if (!root) return 0;
	int lh = BiTreeDepth(root->lchild);
	int rh = BiTreeDepth(root->rchild);
	return lh > rh ? lh + 1 : rh + 1;
}

void operate()
{
	BiTree MyBiTree;
	printf("请输入节点序列(注:①输入连续‘#’个数m大于连续的字母个数n时前第m-1个节点无左右孩子;\n\
		    ②连续的#个数x-1=y是用来划分前第y个字母左右子树的。):\n");
	Create(MyBiTree);	//创建树
	printf("先序遍历树:");
	Preorder(MyBiTree);	//先序遍历树
	printf("\n");
	printf("先序遍历树:");
	Inorder(MyBiTree);	//中序遍历树
	printf("\n");
	printf("先序遍历树:");
	Postorder(MyBiTree);	//后续遍历树
	printf("\n");
	printf("叶子结点:");
	Preorderleaf(MyBiTree);
	printf("\n");
	printf("叶子节点的个数为:%d\n", LeafCount(MyBiTree));
	printf("树的深度为:%d\n", BiTreeDepth(MyBiTree));
}

int main()
{
	operate()<span style="font-family: Arial, Helvetica, sans-serif;">;</span>
	return 0;
}
 

输入示例:

 

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值