Binary tree (6)----traversing a binary tree by layer

Source: Internet
Author: User

1. Binary Tree definition

typedef struct BTREENODEELEMENT_T_ {    void *data;} btreenodeelement_t;typedef struct Btreenode_t_ {    btreenodeelement_t *m_pelemt;    struct Btreenode_t_    *m_pleft;    struct btreenode_t_    *m_pright;} btreenode_t;


2. Traverse the binary tree by layer


The first step: need to use the queue, first the root node proot queued;

Second step: When the queue is not empty, get the first element of the team and out of the team, assigned to Proot, the third step;

The third step: if the Proot left node exists, then the queue; if the proot right node exists, then the queue; second step.


void  Leveltraverse (btreenode_t *proot) {    if (proot = = NULL)        return;    Queue <btreenode_t *>  que;    Que.push (proot);    while (!que.empty ()) {        proot = Que.front ();        Que.pop ();        Visit (proot);        if (proot->m_pleft! = NULL)            que.push (proot->m_pleft);        if (proot->m_pright! = NULL)            que.push (proot->m_pright);    }    return;}


Binary tree (6)----traversing a binary tree by layer

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.