题目:
Description
给定一个二叉树,获取该二叉树的宽度深度。Prototype
int GetBiNodeInfo(BiNode &head, unsigned int *pulWidth, unsigned int *pulHeight)
Input Param
head 需要获取深度的二叉树头结点
Output Param
pulWidth 宽度
pulHeight 高度
Return Value
0 成功
1 失败或其他异常
分析:使用二叉树的层序遍历,使用队列很简单的解决问题
代码如下:
int GetBiNodeInfo(BiNode &head, unsigned int *pulWidth, unsigned int *pulHeight)
{
/*在这里实现功能*/
if(&head==NULL)
return -1;
*pulWidth=0;
*pulHeight=0;
queue<BiNode*> biStack;
biStack.push(&head);
while(!biStack.empty()){
++(*pulHeight);
if(biStack.size()>*pulWidth)
*pulWidth=biStack.size();
int i=biStack.size();
while(i>0){
BiNode * temp=biStack.front();
biStack.pop();
if(temp->left!=NULL)
biStack.push(temp->left);
if(temp->right!=NULL)
biStack.push(temp->right);
i--;
}
}
printf("pulWidth=%d\n pulHeight=%d\n",*pulWidth,*pulHeight);
return 0;
}