Non-recursive traversal implementation of binary tree sequence, middle sequence and sequential order (C language)

Source: Internet
Author: User

First , non-recursive sequential traversal

void Treversepreorder (struct btree *t)
{struct btree
    ;
    int top=0;
    while (p| | Top)
    {
        if (p)
        {
            printf ("%d", p->data);
            stack[top++]=p;
            p=p->left;
        }
        else
        {
            p=stack[--top];
            p=p->right;}}}

second, non-recursive sequence traversal

void Treverseinorder (struct btree *t)
{struct btree
    ;
    int top=0;
    while (p| | Top)
    {
        if (p)
        {
            stack[top++]=p;
            p=p->left;
        }
        else
        {
            p=stack[--top];
            printf ("%d", p->data);
            p=p->right;}}}

third, non-recursive subsequent traversal

void treversepostorder (struct btree *t) {struct btree;
    int top=0; while (p| |
            Top) {if (p) {stack[top++]=p;
        p=p->left;
            } else {p=stack[top-1];
                if (p->right&&p->right!=r)//Right subtree, not empty and not accessed, you need to traverse {p=p->right;
            stack[top++]=p;//Current Right sub-tree pressure stack p=p->left;
                else//the right subtree is empty, direct access to {P=stack[--top];
                printf ("%d", p->data);
            R=P;//R Save node P=null; }
        }
    }
}

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.