Binary tree (9)----The first m node of the K-layer in the printed binary tree, the non-recursive algorithm

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. Find the M-node of the K-layer in the binary tree

(1) Non-recursive algorithm

With queue implementation

First proot the given root node to the queue:

The first step: Get the current queue length, that is, the total number of nodes in the current layer;

The second step: according to the total number of nodes in the current layer, to go out of the queue, traverse the current layer of all nodes, and the current node of the left and right nodes into the queue, the lower node is queued; At the time of traversal, record the number of layers, and the order of nodes, and return this node when the number of layers and order

The third step: After the loop ends, NULL is returned if there are no eligible nodes.


btreenode_t   Getkthlevelmthnode (btreenode_t *proot, int kthlevel, int mthnode) {    if (proot = = NULL | | Kthlevel <= 0 | | Mthnode <= 0)        return NULL;    Queue <btreenode_t *> que;    int level = 1;    int cntnode = 0;    int curleveltotal = 0;    Que.push (proot);    while (!que.empty ()) {        curleveltotal = Que.size ();        while (Cntnode < curleveltotal) {            ++cntnode;            Proot = Que.front ();            Que.pop ();                    if (level = = Kthlevel  && cntnode = = Mthnode)                return proot;            if (proot->m_pleft)                Que.push (proot->m_pleft);            if (proot->m_pright)                Que.push (proot->m_right);        }        Cntnode = 0;        ++level;    }    return NULL;}



Two fork Tree (9)----Print the first m node of the K-layer in a binary tree, non-recursive algorithm

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.