Binary tree (2)----sequence traversal, recursive and non-recursive implementations

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, Middle sequence traversal

Definition: First access the left subtree, then access the root node, and finally access the right subtree


(1) Recursive implementation

If the root node is null, the return

If the root node is not NULL, the left subtree is first accessed, then the root node is accessed, and the right subtree is accessed last


void Inordertraverse (btreenode_t *proot) {    if (proot = = NULL)        return;    Inordertraverse (proot->m_pleft);    Visiste (proot);    Inordertraverse (proot->m_pright);}


(2) Non-recursive implementation

The first step: given the root node proot, determine whether the proot is empty, if not empty, then take the second step, if it is empty, then the third step;

The second step: the Proot into the stack, the Proot left node assigned to Proot, and then the first step;

The third step: Determine whether the stack is empty, if it is empty, then the end, if not empty, then remove the top of the stack to Proot, and out of the stack, access to Proot, and then assign the right node of Proot to Proot, and then take the first step.


void  Inordertraverse (btreenode_t *proot) {    if (proot = = NULL)        return;    Stack < btreenode_t *> St;    while (proot! = NULL | |!st.empty ()) {        while (proot! = null) {            st.push (proot);            Proot = proot->m_pleft;        }        if (!st.empty ()) {            proot = St.top ();            St.pop ();            Visit (proot);            Proot = proot->m_pright;        }    }    return;}


Binary tree (2)----sequence traversal, recursive and non-recursive implementations

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.