一、二叉树宽度
利用队列保存每一层的结点,借助层次遍历的思想(先将根节点入队,队列非空时每出队一个结点将其左右子节点入队),队列中的结点个数就是下一次的循环次数,当循环结束后队列中的结点就全部是下一层的结点。
int width(BTree t)
{
if(t==NULL) return 0;
queue <BNode*> que;
que.push(t);
int len;
int width=1; //非空时,第一层只有根节点
BNode *tmp;
while(!que.empty())
{
len=que.size(); //当前队列中元素个数,即某一层结点的个数
while(len>0) //当前层结点依次出队
{
tmp=que.front(); //返回队首元素
que.pop(); //pop函数返回值是void
if(tmp->lchild)
que.push(tmp->lchild);
if(tmp->rchild)
que.push(tmp->rchild);
len--;
}
width=max(width,(int)que.size()); //比较下一层的宽度和已知最大宽度
}
return width;
}
二、二叉树高度
递归调用计算树的左子树高度和右子树高度,取其较大者加1。
int height(BTree t)
{
if(t==NULL) return 0;
int left=height(t->lchild)+1;
int right=height(t->rchild)+1;
return max(left,right);
}