来自大佬群主的第二题

所谓层次遍历,是将二叉树中的元素从根节点按照节点层数一层层的输出。
代码如下:
int GetDepth(bitreenode *root)
{
int depth=0;
bitreenode *p=root;
queue<bitreenode*> q;
q.push(p); //根指针入队
while(!q.empty())
{
depth++; //高度加一
int width=q.size(); //获取当前层次宽度
for(int i=0;i<width;i++)
{
p=q.front(); //获取队顶元素
q.pop(); //弹出队顶元素
if(p->leftchild!=NULL) //左孩子入队
q.push(p->leftchild);
if(p->rightchild!=NULL) //右孩子入队
q.push(p->rightchild);
}
}
cout<<depth<<endl;
}
本文介绍了一种二叉树的层次遍历方法,并通过具体的C++代码实现了该算法。层次遍历是从根节点开始,按层从左到右依次访问二叉树中的节点。
2038





