#include <stdio.h>
#include<malloc.h>
#define ENDKEY 0
typedef int KeyType;
typedef struct node
{
KeyType key ; /*關鍵字的值*/
struct node *lchild,*rchild;/*左右指標*/
}BSTNode, *BSTree;
void InsertBST(BSTree *bst, KeyType key)
/*若在二叉排序樹中不存在關鍵字等于key的元素,插入該元素*/
{
BSTree s;
if (*bst == NULL)/*遞回結束條件*/
{
s=(BSTree)malloc(sizeof(BSTNode));/*申請新的結點s*/
s-> key=key;
s->lchild=NULL;
s->rchild=NULL;
*bst=s;
}
else
if (key < (*bst)->key)
InsertBST(&((*bst)->lchild), key);/*將s插入左子樹*/
else
if (key > (*bst)->key)
InsertBST(&((*bst)->rchild), key); /*將s插入右子樹*/
}
void CreateBST(BSTree *bst)
/*從鍵盤輸入元素的值,創建相應的二叉排序樹*/
{
KeyType key;
*bst=NULL;
scanf("%d", &key);
while (key!=ENDKEY) /*ENDKEY為自定義常量*/
{
InsertBST(bst, key);
scanf("%d", &key);
}
}
//先序遍歷二叉樹
void PreOrder(BSTree root)
/*先序遍歷二叉樹, root為指向二叉樹根結點的指標*/
{
if (root!=NULL)
{
printf("%d ",root->key); /*輸出結點*/
PreOrder(root->lchild); /*先序遍歷左子樹*/
PreOrder(root->rchild); /*先序遍歷右子樹*/
}
}
//遞回
BSTree SearchBST(BSTree bst, KeyType key)
//在根指標bst所指二叉排序樹中,遞回查找某關鍵字等于key的元素,若查找成功,回傳指向該元素結點指標,否則回傳空指標
{
if (!bst)
return NULL;
else
if (bst->key == key)
return bst;//查找成功
else
if (bst->key > key)
return SearchBST(bst->lchild, key);//在左子樹繼續查找
else
return SearchBST(bst->rchild, key);//在右子樹繼續查找
}
//非遞回
BSTree searchbst(BSTree bst, KeyType key)
/*在根指標bst所指二叉排序樹bst上,查找關鍵字等于key的結點,若查找成功,回傳指向該元素結點指標,否則回傳空指標*/
{
BSTree q;
q=bst;
while(q)
{
if (q->key == key)
return q; /*查找成功*/
if (q->key > key)
q=q->lchild; /*在左子樹中查找*/
else
q=q->rchild; /*在右子樹中查找*/
}
return NULL; /*查找失敗*/
}/*SearchBST*/
void main()
{
BSTree T;
int k;
printf("建立二叉排序樹,請輸入序列:\n");
CreateBST(&T);
printf("先序遍歷輸出序列為:");
PreOrder(T);
//查找
printf("\n請輸入要查找的元素:");
scanf("%d",&k);
fflush(stdin);
SearchBST(T,k);
if( SearchBST(T,k)!= NULL)
printf("此元素的位置為:%d",SearchBST(T,k));
else
printf("未找到!\n");
searchbst(T,k);
if( searchbst(T,k)!= NULL)
printf("此元素的位置為:%d",searchbst(T,k));
else
printf("未找到!\n");
}怎么才能把查找的數的位置是第幾個執行出來啊,其他的不改,主函式怎么改一下可以輸出查找的數是第幾個位置
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/229583.html
標籤:C語言
