二叉树的层序遍历 使用队列和不使用队列

来源:互联网 发布:怎么管理mac下面的图标 编辑:程序博客网 时间:2024/06/05 21:00

1、使用队列

先将树的根节点入队,
如果队列不空,则进入循环
{
将队首元素出队,并输出它;
如果该队首元素有左孩子,则将其左孩子入队;
如果该队首元素有右孩子,则将其右孩子入队
}
C语言代码:

void LevelOrderTraverse(BiTree T,Status(*Visit)(TElemType))  {      //Visit是对节点操作的应用函数,      //在这里,对每个数据元素调用函数Visit,也即是遍历了该节点         SqQueue q;      QElemType p;      if(T)      {          InitQueue(&q);          EnQueue(&q,T);          while(!QueueEmpty(q))          {              DeQueue(&q,&p);              Visit(p->data);              if(p->lchild!=NULL) EnQueue(&q,p->lchild);              if(p->rchild!=NULL) EnQueue(&q,p->rchild);          }          printf("/n");      }  }  

2、不使用队列
C语言代码:

void LevelorderTraversal(BinTree BT){    if(BT)    {        BinTree b[100];        b[0] = BT;        int first = 0;        int rear = 1;        while(first < rear)        {            printf(" %c",b[first]->Data);            if(b[first]->Left)            {                b[rear++] = b[first]->Left;            }            if(b[first]->Right)            {                b[rear++] = b[first]->Right;            }            first++;        }    }}
阅读全文
0 0
原创粉丝点击