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