1.递归法求解高度
int Height(node *p)
{
int height=0;
if(p!=NULL)
{
int leftHeight=Height(p->left);
int rightHeight=Height(p->right);
height=leftHeight>rightHeight?leftHeight+1:rightHeight+1;
}
return height;
}
2.求二叉树的宽度,利用队列
//求二叉树的宽度
int treeWidth(BinaryTreeNode *pRoot){
if (pRoot == NULL)
return 0;
int nLastLevelWidth = 0;//记录上一层的宽度
int nCurLevelWidth = 0;//记录当前层的宽度
queue<BinaryTreeNode*> myQueue;
myQueue.push(pRoot);//将根节点入队列
int nWidth = 1;//二叉树的宽度
nLastLevelWidth = 1;
BinaryTreeNode *pCur = NULL;
while (!myQueue.empty())//队列不空
{
while (nLastLevelWidth!= 0){
pCur = myQueue.front();//取出队列头元素
myQueue.pop();//将队列头元素出对
if (pCur->m_pLeft != NULL)
myQueue.push(pCur->m_pLeft);
if (pCur->m_pRight != NULL)
myQueue.push(pCur->m_pRight);
nLastLevelWidth--; //保证遍历的结点个数是上层的个数
}
nCurLevelWidth = myQueue.size();
nWidth = nCurLevelWidth > nWidth ? nCurLevelWidth : nWidth;
nLastLevelWidth = nCurLevelWidth;
}
return nWidth;
}
ps:在这个问题的求解方面还有另一种利用双端队列的解决方法,我目前不懂啊,就不写啦,感兴趣的可以自己查一下。
给出一个链接:http://blog.csdn.net/shf4715/article/details/47052385