求二叉数的深度和宽度

        二叉树的深度:二叉树的根结点所在的层数为1,根结点的孩子结点所在的层数为2,以此下去。深度是指所有结点中最深的结点所在的层数。

        二叉树的宽度:所有深度中含有的最多的子叶数。

        参考文献:http://blog.csdn.net/htyurencaotang/article/details/12406223#comments

        1.C++

//求二叉树的深度
int GetDepth(tagBiNode *pRoot)
{
	if (pRoot == NULL)
	{
		return 0;
	}

	// 	int nLeftLength = GetDepth(pRoot->m_left);
	// 	int nRigthLength = GetDepth(pRoot->m_right);
	// 	return nLeftLength > nRigthLength ? (nLeftLength + 1) : (nRigthLength + 1);

	return GetDepth(pRoot->left) > GetDepth(pRoot->right) ? 
		(GetDepth(pRoot->left) + 1) : (GetDepth(pRoot->right) + 1);
}

//求二叉树的宽度
int GetWidth(tagBiNode *pRoot)
{
	if (pRoot == NULL)
	{
		return 0;
	}

	int nLastLevelWidth = 0;//记录上一层的宽度
	int nTempLastLevelWidth = 0;
	int nCurLevelWidth = 0;//记录当前层的宽度
	int nWidth = 1;//二叉树的宽度
    queue<BiNode *> myQueue;
	myQueue.push(pRoot);//将根节点入队列
	nLastLevelWidth = 1;	
	tagBiNode *pCur = NULL;

	while (!myQueue.empty())//队列不空
	{
		nTempLastLevelWidth = nLastLevelWidth;
		while (nTempLastLevelWidth != 0)
		{
            pCur = myQueue.front();//取出队列头元素
			myQueue.pop();//将队列头元素出对

			if (pCur->left != NULL)
			{
				myQueue.push(pCur->left);
			}

			if (pCur->right != NULL)
			{
				myQueue.push(pCur->right);
			}

			nTempLastLevelWidth--;
		}

		nCurLevelWidth = myQueue.size();
		nWidth = nCurLevelWidth > nWidth ? nCurLevelWidth : nWidth;
		nLastLevelWidth = nCurLevelWidth;
	}

	return nWidth;
}
        2.Java

	public static int getHeight(BiNode head)
	{
		int deep = 0;
		if(head != null)
		{
			int left = getHeight(head.left);
			int right = getHeight(head.right);
			deep = (left>=right)?(left+1):(right+1);
		}
		return deep;
	}
	public static int getWidth(BiNode head)
	{
		if(head == null)
		{
			return 0;
		}
		
		int nWidth = 0;
		int nLastLevelWidth = 0;
		int nTempLastLevelWidth = 0;
		int nCurLevelWidth = 0; 
		
		Queue<BiNode> myQueue = new LinkedList<Demo.BiNode>();
		myQueue.add(head);
		nLastLevelWidth = 1;
		nWidth = 1;
		
		while(!myQueue.isEmpty())
		{
			nTempLastLevelWidth = nLastLevelWidth;
			BiNode tmp = null;
			while(nTempLastLevelWidth != 0)
			{
				tmp = myQueue.peek();
				myQueue.poll();

				if(tmp.left != null)
				{
					myQueue.add(tmp.left);
				}
				if(tmp.right != null)
				{
					myQueue.add(tmp.right);
				}
				nTempLastLevelWidth--;
			}
			
			nCurLevelWidth = myQueue.size();
			nWidth = nCurLevelWidth>nWidth?nCurLevelWidth:nWidth;
			nLastLevelWidth = nCurLevelWidth;
		}
		return nWidth;
	}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值