2015年大二上-数据结构-查找-1-(4)-二叉树排序树中查找的路径
2016-03-04 13:27
441 查看
/* *Copyright (c) 2014,烟台大学计算机学院 *All rights reserved. *文件名称:Annpion.cpp *作者:王耀鹏 *完成日期:2016年3月4日 *版本号:v1.0 * *问题描述:二叉树排序树中查找的路径 *输入描述:二叉排序树 *输出描述:二叉树排序树中查找的路径 */ #include <stdio.h> #include<malloc.h> #define MaxSize 100 typedef int KeyType; typedef char InfoType[10]; typedef struct node { KeyType key; InfoType data; struct node *lchild,*rchild; } BSTNode; int path[MaxSize]; //全局变量,用于存放路径 int InsertBST(BSTNode *&p,KeyType k) //在p所指向的二叉排序树中,插入值为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) InsertBST(p->lchild,k); else InsertBST(p->rchild,k); } BSTNode *CreateBST(KeyType A[],int n) //由有n个元素的数组A,创建一个二叉排序树,返回BST树根结点指针 { BSTNode *bt=NULL; int i=0; while(i<n) { InsertBST(bt,A[i]); ++i; } return bt; } int SearchBST(BSTNode *bt,KeyType k,KeyType path[],int i)//在二叉排序树中查找,记经过的节点记录在path中,返回值为最后查找节点在path中存储的下标 { if(bt==NULL) return i; else if(bt->key==k) { 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,i; r=SearchBST(bt,k1,path,-1); for(i=0;i<=r;++i) printf("%3d",path[i]); 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=CreateBST(a,n); DispBST(bt); printf("\n"); printf(" 查找%d关键字:",k1); SearchResult(bt,k1); printf(" 查找%d关键字:",k2); SearchResult(bt,k2); return 0; }
运行结果:
相关文章推荐
- 常用的数据结构及其算法
- 数据结构
- 网易云数据结构- Maximum Subsequence Sum
- 网易云数据结构-最大子列和问题
- 数据结构基础
- 数据结构基本八大排序算法
- Redis各种数据结构内存占用测试
- 2015年大二上-数据结构-查找-1-(3)-二叉排序树
- 数据结构(17)--图的遍历DFS和BFS
- 数据结构学习之队列
- 6-5-树的双亲表示法-树和二叉树-第6章-《数据结构》课本源码-严蔚敏吴伟民版
- SPL的常用数据结构(2)
- 数据结构(1):顺序表
- 数据结构——线性表
- c语言实现求最短路径(迪杰斯特拉算法,《数据结构》算法7.15)
- 2015年大二上-数据结构-查找-1-(2)-分块查找
- 2015年大二上-数据结构-查找-1-(1)-线性表的折半查找
- 数据结构(16)--图的存储及实现
- 《数据结构》双向链表的创建
- HashMap的实现原理和底层数据结构