A non-recursive algorithm for the sequence traversal of binary tree _c language

Source: Internet
Author: User
The forward traversal of the binary tree is the first root node, and then if there is a Zuozi, then the left subtree is first ordered, then the right subtree is followed by its subtree.
The recursive algorithm is as follows
Copy Code code as follows:

void preorder (Betree *t)
{if (t==null) return;visit (t);//access the node preorder (t->lchild);p reorder (t->rchild);}

The recursive algorithm, of course, implicitly uses the stack. We carefully analyze this process, first took out the root node for access, and then we put the root node back stack, after the stack must have nodes into the stack, how to do? Root node can only directly access to Rchild and lchild, if it is Zuozi root node into the stack, then it is inevitable to visit, so it is rchild advanced stack, Lchild backward stack. Can draw a deeper understanding of the drawing.
So now write the first sequence traversal of the binary tree algorithm.
Copy Code code as follows:

void preorder (Betree *t)
{//algorithm we use one-dimensional arrays to simulate a sequential stack
      if (t==null) return;//is empty tree there is absolutely no need to do the following     
     Betree * Stack[max];
     top=1;stack[top]=t;//root node into stack
     while (top>0)
     {   nd=stack[top];//Remove the root node   top=top-1;//back stack    visit (nd->data);//Access root node if (nd- >rchild!=null {Top=top+1;stack[top]=nd->rchild}////root node has right subtree, put it into stack, wait until Zuozi is finished accessing
if (nd->lchild!=null) { Top=top+1;stack[top]=nd->lchild;}
  }
}

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.