二叉树的宽度、高度、叶子数、复制

采用层次遍历的方法

int width(BiTree T)
{
	if(T==NULL)	return 0;
	else
	{
		BiTree Q[]; //Q队列,元素为二叉树结点指针
		front=1;rear=1;
		last=1;	//同层最右结点在队列中的位置
		t=0,maxw=0; //t记录局部宽度
		Q[rear]=T; 
		while(front<=last)
		{
			p=Q[front++]; 
			t++;   	// 同层元素数加一
			if(p->lchild!=NULL)
				Q[++rear]=p->lchild;
			if(p->rchild!=NULL)
				Q[++rear]=p->rchild;
			if(front>last)
			{
				last=rear;  //last指向下层最右元素
				if(t>maxw)
					maxw=t;
				t=0;
				}	
		}	
	}
		return maxw;
}

高度递归算法

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 Lleaf(Bitree T)
{
	if(T==NULL)	return 0;
	if(T->lchild==NULL&&T->rchild==NULL)
		retutn 1;
	else return Leaf(T->lchild)+Leaf(T->rchild);	
}

复制二叉树

int Copy(BiTree T, BiTree &NewT)
{
	if(T==NULL)	   
	{
		NewT==NULL;return 0;
	}
	else
	{
		NewT= New BiTNode;
		NewT->data=T->data;
		Copy(T->lchild,NewT->lchild);
		Copy(T->rchild,NewT->rchild);
	}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值