二叉树的层次遍历是通过一个队列来实现,先让根节点入队列,然后出队列,将出队列的值打印出来,并将这个值得左右子节点入队列,开始的时候只要有出队列就有两个子节点入队列,最后的时候到了叶子节点,就全是出队列了;
代码比较简单,如下:
void travBiTree3(Node *head)//层次遍历
{
if (head==NULL)
{
return;
}
queue q;
Node *temp=NULL;
q.push(head);
while(!q.empty())
{
q.pop(temp);
cout<<temp->val<<"\t";
if (temp->left)
{
q.push(temp->left);
}
if (temp->right)
{
q.push(temp->right);
}
}
}