求二叉树的宽度

2)求二叉树的宽度

我们可以把二叉树中每层的节点依次放入一个队列中。设置一个变量width用于存储树的宽度。每一层的节点入队时计算该层节点的数目,如果该层次节点的数目大于width的值,那么把该层次节点的数目赋给width.如此,对二叉树按层遍历一遍之后width中保存的就是该二叉树的宽度。

int WidthOfTheTree(Node* pRoot)
{
	if(pRoot==NULL)
		return 0;
	queue<Node*> MyQueue2;
	MyQueue2.push(pRoot);
	int width=1;
	int curwidth=1;
	int nextwidth=0;
	while(!MyQueue2.empty())
	{
		while(curwidth!=0)
		{
			Node* pTmp=MyQueue2.front();
			MyQueue2.pop();
			curwidth--;
			if(pTmp->pLeft!=NULL)
			{
				MyQueue2.push(pTmp->pLeft);
				nextwidth++;
			}
			if (pTmp->pRight!=NULL)
			{
				MyQueue2.push(pTmp->pRight);
				nextwidth++;
			}
		}
		if(nextwidth>width)
			width=nextwidth;
		curwidth=nextwidth;
		nextwidth=0;
	}
	return width;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值