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:
- How to calculate a complete round of operations.
- How the current state is saved during the operation to ensure later access.
- 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