The pre-order establishment of binary tree and the non-recursive algorithm of pre-sequence traversal

Source: Internet
Author: User

The recursive algorithm of binary tree and the recursive algorithm of pre-order traversal are all well-known, and the recursive algorithm is very convenient for writing code. However, sometimes we do need their non-recursive algorithms. Translating recursive algorithms into non-recursive algorithms can help us to understand the principles of function invocation and stack. Here is a summary of these important non-recursive algorithms for binary trees.

I. Pre-order Achievements

The basic idea of a pre-order build is to receive a set of strings that the user enters, where ' # ' stands for empty trees and other data field values that represent the tree nodes. For example, to create a tree like this


You need to enter "ab#d# #C # #".

Instead of recursive thinking is, 1, set a flag to determine whether the node currently created is left child or right child. 2, with a stack record has been created a good node, when a node created after the completion of the pressure stack, the purpose is to play the stack after the child to create its left and right. 3, the first step is to stack the root node, and then loop. When the stack is empty, it indicates that the tree has been created. 4, if the current traversal to the data is #, then there are two things to do. On the one hand, if the current flag bit indicates that the left child is being created, then change it to create right child. On the other hand, the stack lets the pointer point to the top element of the stack and prepares to create its right child. In other words, when # comes up, either the build is done or the right child is created.

The specific code is as follows

Status Precreatebitree (Bitree *t) {Stack S;    Bitnode *p;    Char Buff[max_buff_size];        Fgets (buff, sizeof (buff), stdin);        Initstack (&s);    char *buffptr = buff;    if (*buffptr = = ' # ') {return no_tree;    } *t = (bitree) malloc (sizeof (Bitnode));    if (!*t) {exit (OVERFLOW);    } p = *t;    (*t)->data = *buffptr;    buffptr++;        Push (&s, *t);    BOOL iscreatingright = FALSE; for (int i = 0; (*BUFFPTR); i++) {if (*buffptr! = ' # ') {//If the current node is not empty//If you are creating a left child, enter the stack if (iscreatin                Gright = = FALSE) {Bitnode *newnode = (bitree) malloc (sizeof (Bitnode));                Newnode->data = *buffptr;                P->lchild = NewNode;                p = newNode;            Push (&s, NewNode);                } else {//The right child is created at this time, into the stack, and the flag is false bitnode *newnode = (bitree) malloc (sizeof (Bitnode)); Newnode->data = *BUFFPTR                P->rchild = NewNode;                p = newNode;                Push (&s, NewNode);            Iscreatingright = FALSE; }} else {//If the current node is empty, bounce//If the left child is being created, the stack creates the right child if (iscreatingright = =            FALSE) {iscreatingright = TRUE;            }//If the tree has been created, break out if (Stackempty (S)) {break;            } else {//Let P point to the top of the stack element, ready to create its right child Pop (&s, &p);    }} buffptr++; } return OK;


Second, pre-sequence traversal

Idea: The pre-sequence traversal is characterized by the first traversal of the root, then the left child, after the right child. So we can have a pointer p point to the tree root, output tree root information, "(analysis) then point to its left child, output, and then point to the left child output ... Until the point is empty, if so, how to find the right child? "To ensure that every time you traverse the left child without" losing touch "with the right child, you can stack the root node, and when you need to traverse the right child, the stack points to the right child.

Specific code:

Status Preordertraverse (Bitree T) {    Stack S;    Initstack (&s);    Bitree p = T;    while (P! = NULL | |! Stackempty (S)) {        if (P! = NULL) {            printf ("%c", p->data);                      First, traverse the root node            Push (&s, p);            p = p->lchild;                              Access left subtree        } else {                                        //current node is empty, then go to right subtree            Pop (&s, &p);            p = p->rchild;        }    }        printf ("\ n");        return OK;}


third, middle sequence traversal

Idea: basically similar to the previous sequence. The characteristic of the middle order is the first left subtree, then the root tree, and finally the right subtree. So we need to find the left child first, again, in order not to lose the link with the right child, each point to the left child before pressing the stack. The only thing to note is that when p points to null, it indicates that the leftmost is found and should be output. Then the stack is then output, because if the stack is not playing, because P is currently referring to null;

Specific code:

Status Inordertraverse (Bitree T) {    Stack S;    Initstack (&s);    Bitree p = T;    while (P! = NULL | |! Stackempty (S)) {        if (P! = NULL) {            Push (&s, p);            p = p->lchild;                              Find the leftmost node        } else {                                        //When the left dial hand tree is empty            Pop (&s, &p);            printf ("%c", p->data);                      Outputs the current node, representing the first output left node            p = p->rchild;                              . Then go to the right subtree        }    }        printf ("\ n");        return OK;}

Third, post-sequential traversal

Idea: The most troublesome is the post-sequential traversal. Why bother, the post-sequential traversal is characterized by first left subtree, then right subtree, and then the root of the tree. We need to find the left dial hand tree through the roots, and then we need the roots to find the right subtree. In other words, we will encounter two times the stack to the root of the situation, respectively, from the left child and the right child back. So we need a sign to show exactly which child came back from. If it is the left child, then the root of the task is not finished, but also rely on it to find the right child, so re-pressure stack, if the right child, you can output roots. Note that after the root is finally output, p points to null, which is intended to continue to access the parent root node of p at the next iteration of the stack.

The logo here is not as simple as the achievements, we use the idea is to set up two stacks, one is a normal tree node stack, another represents the left and right child marker bit stack. The operation of the two stacks is synchronized, that is, when the left child into the stack is, the flag bit stack is also pressed into a sign to the left child's node. Similarly, when the stack is stacked, the flag stack is stacked and judged to be the left child or the right child.

Specific code:

Status Postordertraverse (Bitree T) {//post-order traversal, respectively, from the Saozi right subtree two times back to the root node///Only when the right subtree returns to the root node is traversed by the root node//So add a stack of tokens to reach the node sequence STAC                                       K S, Tag;                    Tag storage flag bit Bitree temp, left, right, p = T;    Left and right are flag bits, and temp is used to detect whether to go from left or right to left = (Bitnode *) malloc (sizeof (Bitnode));    Left->data = 1;    Left->lchild = NULL;    Left->rchild = NULL;    right = (Bitnode *) malloc (sizeof (Bitnode));    Right->data = 2;    Right->lchild = NULL;        Right->rchild = NULL;    Initstack (&s);                                    Initstack (&tag); Flag bit stack, 1 when returned from Zuozi, 2 while when returning from right subtree (p! = NULL | |!            Stackempty (S)) {if (P! = NULL) {Push (&s, p);                           Push (&tag, left);        The first time into the stack, at this time the flag bit pressure is left child sign p = p->lchild;            } else {Pop (&s, &p);                        Pop (&tag, &temp); if (temp = = left) {//if theThe tree returns, then the second time into the stack, at this time the flag bit pressure is right child sign Push (&s, p);                Push (&tag, right);            p = p->rchild;                } else {//return from right subtree, direct access to root node printf ("%c", p->data);                               p = NULL;        The goal is to allow the next step to be rolled back, thus accessing the root node}} printf ("\ n"); return OK;}



The pre-order establishment of binary tree and the non-recursive algorithm of pre-sequence traversal

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.