【项目 - 二叉树排序树中查找的路径】
设计一个算法,输出在二叉排序中查找时查找某个关键字经过的路径。
[参考解答]
专为本项目设计的算法体现在函数int SearchBST(…)和void SearchResult()中。
#include <stdio.h>#include <malloc.h>#define MaxSize 100typedef int KeyType; typedef char InfoType;typedef struct node { KeyType key; InfoType data; struct node *lchild,*rchild; } BSTNode;int path[MaxSize]; void DispBST(BSTNode *b); int InsertBST(BSTNode *&p,KeyType k) { if (p==NULL) { 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) return InsertBST(p->lchild,k); else return InsertBST(p->rchild,k); }BSTNode *CreatBST(KeyType A[],int n){ BSTNode *bt=NULL; int i=0; while (i<n) InsertBST(bt,A[i++]); return bt; }int SearchBST(BSTNode *bt,KeyType k,KeyType path[],int i){ if (bt==NULL) return i; else if (k==bt->key) { path[i+1]=bt->key; return i+1; } else { path[i+1]=bt->key; if (k<bt->key) SearchBST(bt->lchild,k,path,i+1); else SearchBST(bt->rchild,k,path,i+1); }}void SearchResult(BSTNode *bt, int k1){ int r, j; r = SearchBST(bt,k1,path,-1); for (j=0; j<=r; j++) printf("%3d",path[j]); printf("\n");}void DispBST(BSTNode *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(")"); } }}int main(){ BSTNode *bt; KeyType k1=65, k2=32; int a[]= {43,91,10,18,82,65,33,59,27,73},n=10; printf("创建的BST树:"); bt=CreatBST(a,n); DispBST(bt); printf("\n"); printf(" 查找%d关键字:",k1); SearchResult(bt,k1); printf(" 查找%d关键字:",k2); SearchResult(bt,k2); return 0;
}