We can use a lot of ways to traverse a binary tree, such as first-order traversal, in-sequence traversal, after the next traversal, in fact, are implemented by recursion. Today we have a sequence traversal of the two-fork tree, which requires the use of another data structure-the queue. The sample code for this article is uploaded to Https://github.com/chenyufeng1991/LevelOrderBinaryTree.
The basic idea of sequence traversal is that when accessing a node, put it into the queue and then access the value, and put the node's left and right child nodes in the queue, out of the queue that node. It should be noted that if a node is already a leaf node, it does not need to put its left and right child node (although it does not have children) into the queue. Because the push of an empty node into the queue can cause a bug. Similarly, if it has only a left child or only a right child, it is the same treatment. The condition at which recursion ends is when the queue is empty.
The core code is as follows:
Sequence traversal
void Levelorder (Queue<node *> &nodequeue)
{
if (Nodequeue.empty ()) {return
;
}
Node *frontnode = Nodequeue.front ();
cout << frontnode->element << "";
Nodequeue.pop ();
if (frontnode->lchild!= NULL)
{
nodequeue.push (frontnode->lchild);
}
if (frontnode->rchild!= NULL)
{
nodequeue.push (frontnode->rchild);
}
Levelorder (Nodequeue);
}