第十四周项目二(二叉树排序树中查找的路径)
来源:互联网 发布:中国电影票房数据库 编辑:程序博客网 时间:2024/05/21 19:48
- *Copyright(c)2016,烟台大学计算机与控制工程学院
- *All right reserved.
- *文件名称:二叉树排序树中查找的路径.cpp
- *作者:宋雨静
- *时间:12月8日
- *版本号;v1.0
- *问题描述:
-
- 设计一个算法,输出在二叉排序中查找时查找某个关键字经过的路径。
- *输入描述:无
- *程序输出:根据要求输出
- */
-
- [cpp] view plain copy
- #include <stdio.h>
- #include <malloc.h>
- #define MaxSize 100
- typedef 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;
- }
运行结果:
0 0