This article is a practical project reference in [Data Structure basic series (8): find].
"Project-Path to find in two tree sort tree"
An algorithm is designed to find the path through which a keyword is searched when looking in a binary sort.
[Reference Solution]
The algorithm designed for this project is embodied in the function int searchbst (...). and void SearchResult ().
#include <stdio.h>#include <malloc.h>#define MaxSizetypedef intKeyType;//define keyword typestypedef CharInfoType;typedef structNode//Record type{KeyType key;//keyword ItemsInfoType data;//Other data fields structNode *lchild,*rchild;//Left child hands} Bstnode;intPath[maxsize];//global variable, for storing pathvoidDispbst (Bstnode *b);//Function DescriptionintInsertbst (Bstnode *&p,keytype k)//Insert a node with the keyword K in BST with *p as the root node{if(P==null)//The original tree is empty, the newly inserted record is the root node{p= (Bstnode *)malloc(sizeof(Bstnode)); p->key=k; p->lchild=p->rchild=null;return 1; }Else if(K==p->key)return 0;Else if(K<p->key)returnInsertbst (P->LCHILD,K);//INSERT INTO *p's record Else returnInsertbst (P->RCHILD,K);//INSERT into the right subtree of *p}bstnode *creatbst (KeyType a[],intN//Set up a binary sort tree from the keywords in array a{Bstnode *bt=null;//Initial BT is empty tree intI=0; while(i<n) Insertbst (bt,a[i++]);//a[i] inserted in binary sort tree T returnBt//Returns the root pointer of the established two-fork sort tree}//Find in binary sort tree, record the node recorded in path, the return value is the subscript that the last lookup node stores in pathintSearchbst (Bstnode *bt,keytype k,keytype path[],inti) {if(Bt==null)returnIElse if(K==bt->key)//found the node{path[i+1]=bt->key;//output its path returni+1; }Else{path[i+1]=bt->key;if(K<bt->key) Searchbst (bt->lchild,k,path,i+1);//In record recursive lookup ElseSearchbst (bt->rchild,k,path,i+1);//Recursive lookup in right subtree}}//Find and show the path passedvoidSearchResult (Bstnode *BT,intK1) {intR, J; R = Searchbst (bt,k1,path,-1); for(j=0; j<=r; J + +)printf("%3d", Path[j]);printf("\ n");}voidDispbst (Bstnode *BT)//parentheses output binary sort tree bt{if(Bt!=null) {printf("%d", Bt->key);if(Bt->lchild!=null | | bt->rchild!=null) {printf("("); Dispbst (Bt->lchild);if(Bt->rchild!=null)printf(","); Dispbst (Bt->rchild);printf(")"); } }}intMain () {Bstnode *bt; KeyType k1= $, k2= +;inta[]= { +, the,Ten, -, the, $, -, -, -, the},n=Ten;printf("created BST Tree:"); Bt=creatbst (A,n); Dispbst (BT);printf("\ n");printf("Find%d keyword:", K1); SearchResult (BT,K1);printf("Find%d keyword:", K2); SearchResult (BT,K2);return 0;}
Data structure Practice--the path found in the two-tree sorting tree