常见的前序、中序、后序都很常见,最近用到了按层遍历,记录一下:

思路:用一个队列来作为辅助空间。依次存储头结点,左节点和右节点。每次循环输出节点的值,直到队列为空这样一来就利用了队列先进先出的性质实现了非递归按层遍历二叉树。

 

具体实现:

void levelOrderTraverse(const BiTree& t)
{
    queue<BiTree> q;
    BiTree p = NULL;
    
    if(t)
    {
        q.push(t);
    }
    while(!q.empty())
    {
        p = q.front();
        q.pop();
        cout<<p->data<<" ";
        if(p->lchild)//左孩子不空,入队列 
        {
            q.push(p->lchild);
        }
        if(p->rchild)//右孩子不空,入队列 
        {
            q.push(p->rchild);
        }
    } 
}

 

相关文章:

  • 2021-10-11
  • 2021-04-18
  • 2022-01-31
  • 2022-01-05
  • 2022-01-02
  • 2021-09-29
  • 2021-07-26
猜你喜欢
  • 2021-08-26
  • 2022-12-23
  • 2021-05-22
  • 2021-10-13
  • 2022-12-23
相关资源
相似解决方案