二叉树的深度:二叉树的根结点所在的层数为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;
- }
- 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;
- }