二叉树算法设计

设计算法求二叉树的结点个数。
void Count(BiNode *root)
{
    if (root) {
         Count(root->lchild);
         number+ +;  //number为数据成员
         Count(root->rchild);
   }
}

左子树中节点的数目+右子树中节点的数目+1

template<class T>
int BiTree<T>::count(BiNode<T>* root)
{
	int number=0;

	if (root==NULL)
		number=0;
	else
		number=count(root->lchild)+count(root->rchild)+1;
	return number;
}
统计叶子节点的数目

1增加一个数据成员,leafcount, 初值为0
2.对树进行遍历。 如果一个节点是叶子,则将leafcount+1;
可以在前序、中序或后序的遍历过程中进行计算。

从根节点出发
判断当前节点是否是叶子节点,如果是,则叶子数+1
否则,在左子树中遍历,并统计叶子节点的数目,在右子树中进行遍历,并统计叶子节点的数目。

template<typename T> 
void BiTree<T>:: countleaf(BiTreeNode<T> * root){
	if (root) {
		if (root->lchild==0 && root->rchild==0)
			leafcount=leafcount+1;
		else
		{
			countleaf(root->lchild);
			countleaf(root->rchild);
		}
	}
	return;
}

左子树中叶子节点的数目+右子树中叶子节点的数目

template<class T>
int BiTree<T>::leafcount(BiNode<T>* root)
{
	int number=0;

	if (root==NULL)
		number=0;
	else if(root->lchild==NULL && root->rchild==NULL)
		number=1;
	else
	    number=leafcount(root->lchild)+leafcount(root->rchild);
	return number;
}
计算树的高度

高度的定义:
max(左子树高度,右子树高度)+1

从根节点出发开始计算,
如果root==NULL, 高度为0;
否则,分别计算左子树的高度;右子树的高度;
返回max(左子树高度,右子树高度)+1

递归的定义:

template<typename T> 
 int BiTree<T>::cal_height(BiTreeNode<T> * root){
	int lheight=0,rheight=0;
	if (root==0)  	
	 return 0;	
	lheight = cal_height(root->lchild);
	rheight = cal_height(root->rchild);
	if (lheight>rheight)	
	   return lheight+1;
	else 		
    	return rheight+1;
}
输出中缀表达式。并加上相应的括号 (a+(b*(c-d)))-(e/f)

基本思想:
中序遍历:
中序遍历左子树前,输出左括号
中序遍历右子树后,输出右括号
如果遍历叶子节点的左右子树,不输出括号
如果遍历根节点的左右子树,不输出括号(否则,会得到形如(a+b)的表达式)

void BiTree<T>::In_Expression(BiNode<T>* root){
	if(root)
	{
  	   if(root!=this->root&&root->lchild!=0&&root->rchild!=0)
   		         cout<<"(";
	   In_Expression(root->lchild);
	   cout<<root->data;
   	   In_Expression(root->rchild);
 	   if(root!=this->root&&root->lchild!=0&&root->rchild!=0)
			cout<<")";
	}
	
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

努力的clz

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值