二叉树高度、结点数统计、左右孩zi交换(c++)

#include<iostream>
using namespace std;
int a, b, c = 0;   //a代表叶子结点,b代表度为1的结点,c代表度为2点结点
typedef struct BiTNode
{
	char data;
	struct BiTNode* rchild, * lchild;
}BiTNode, * BiTree;
void CreatBiTree(BiTree& T, char s[], int& i)
{
	if (s[i] == '0')
		T = NULL;
	else
	{
		T = new BiTNode;
		T->data = s[i];
		CreatBiTree(T->lchild, s, ++i);
		CreatBiTree(T->rchild, s, ++i);
	}
}
int Depth(BiTree T)     //求高度
{
	if (!T)
		return 0;
	else if (!T->lchild && !T->rchild)
		return 1;
	return Depth(T->lchild) >= Depth(T->rchild) ? Depth(T->lchild) + 1 : Depth(T->rchild) + 1;
}
void count(BiTree T)    //统计结点个数
{
	if (T)
	{
		if (T->lchild && T->rchild)
			c++;
		else if (T->lchild || T->rchild)
			b++;
		else
			a++;
		count(T->lchild);
		count(T->rchild);
	}

}
void Change(BiTree& T)     //左右孩子交换
{
	if (T && T->lchild || T->rchild)
	{
		BiTree p = new BiTNode;
		p = T->lchild;
		T->lchild = T->rchild;
		T->rchild = p;
		Change(T->lchild);
		Change(T->rchild);
	}
}
void PreOrder(BiTree T)    //先序遍历
{
	if (T)
	{
		cout << T->data;
		PreOrder(T->lchild);
		PreOrder(T->rchild);
	}
}
int main()
{
	char s[100];
	BiTree T;
	while (cin >> s && s[0] != '0')
	{
		int i = -1;
		CreatBiTree(T, s, ++i);
		cout << "高度为:";
		cout << Depth(T) << endl;
		count(T);
		cout << "各结点个数为:";
		cout << a << " " << b << " " << c;
		cout << endl;
		Change(T);
		cout << "交换结点后先序序列为:";
		PreOrder(T);
	}
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值