您的位置:首页 > 理论基础 > 数据结构算法

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;
}

运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: