C Language Data structure: Recursive alternative-------backtracking algorithm

Source: Internet
Author: User

1. The definition and process of recursion must be clearly understood in order to understand backtracking.

The non-recursive form of recursive algorithm can use backtracking algorithm. The main issues to consider are:

    1. How to calculate a complete round of operations.
    2. How the current state is saved during the operation to ensure later access.
    3. How to return to the first operation that was not performed.

2. Post Code performance:

To traverse a binary tree in the first order:

Btnode *findnode (btnode *b,elementtype x) {//Find nodes with X in binary tree Btnode *p;if (b==null) return Null;else if (b->element==x) Return B;else{p=findnode (B->LEFT,X); if (p!=null) return p;else return FindNode (b->right,x);}}    void prev (Btnode *b) {Btnode *f=b;    int i,j;    U[0]= ' | ';    I=1;    for (;;)        {for (;;)            {j=0;            printf ("%c", f->element); Switch (PD (f)) {case 0: {//When a node is a leaf node, start backtracking J            =1;break;                  } Case 1:{f=f->left;break;                 When a node has left child without right child, access left child} case 2:{f=f->right;break;                When a node has right child without left child access right child} case 3:{u[i++]=f->element;                  When a node has a left child and has a right child, the value of the node is deposited f=f->left;break; to the character array u for later backtracking access to the previous level.          At the same time continue to visit left child}}  if (j==1) break;                            } f=findnode (B,u[i-1]);        Find the corresponding node if (--i==0) break in the original binary tree according to the most recently saved characters in U.                                     f=f->right; At this point, you should access the right node of the backtracking node//stack Operation}}

  

C Language Data structure: Recursive alternative-------backtracking algorithm

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.