第十二周项目4 二叉树排序树中的查找路径

来源:互联网 发布:知识点梳理软件 编辑:程序博客网 时间:2024/05/20 17:40
#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=NULL;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;}

0 0
原创粉丝点击