Sequence traversal Two-fork tree _ two fork tree

Source: Internet
Author: User

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);
}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.