建立一個二叉排序樹,根據(jù)給定值對其實施查找。
二叉排序樹的二叉鏈表存儲表示:
typedef int ElemType;
typedef struct BSTNode
{
ElemType data;
struct BSTNode *lchild,*rchild;
}BSTNode,*BSTree;
函數(shù)接口定義:下面給出了?二叉排序樹創(chuàng)建和搜索?函數(shù)的大部分內(nèi)容,但缺少了一部分(以下劃線____
標(biāo)識出來的部分)。
請先將以下代碼中畫橫線的部分補(bǔ)充完整,然后將完整的函數(shù)BSTInsert
,BSTCreate
,BSTSearch
提交系統(tǒng),完成題目要求的功能。
void BSTInsert( BSTree &T, BSTree s)
{
if(T==NULL)
T=s;
else if(s->datadata)
BSTInsert( ____ ,s);
else
BSTInsert( ____ ,s);
}
void BSTCreate(BSTree &T)
{
ElemType x; BSTree s;
T=NULL;
cin>>x;
while (x!=-1)
{
s=new BSTNode;
s->data=x;
s->lchild=s->rchild=NULL;
BSTInsert( ____ , ____ );
cin>>x;
}
}
BSTree BSTSearch(BSTree T, ElemType k)
{
if(!T || ____ )
return ____ ;
if(kdata)
return BSTSearch( ____ ,k);
else
return BSTSearch ( ____ ,k);
}
該函數(shù)中的參數(shù)說明:
ElemType k
要搜索的值
順序表中第一個數(shù)據(jù)元素存儲在?T.R[1]
int main ()
{ BSTree T,p; int x;
BSTCreate(T);
cin>>x;
p=BSTSearch(T,x);
if(p!=NULL)
{ cout<<"have found!";
cout<<" lchild:";
if(p->lchild) cout<lchild->data;
else cout<<"NULL";
cout<<" rchild:";
if(p->rchild) cout<rchild->data;
else cout<<"NULL";
}
else
cout<<"NOT FOUND!";
return 0;
}
輸入格式:第一行輸入二叉排序樹中結(jié)點的值,以-1結(jié)束。用逐個插入的方式創(chuàng)建二叉排序樹。
第二行輸入一個要查找的值。
輸出格式:找到,輸出have found!
。接著空一格,輸出該結(jié)點左孩子值,后再空一格,輸出該結(jié)點右孩子的值。如果孩子為空,對應(yīng)位置輸出NULL
。
如果沒有找到,輸出NOT FOUND!
。
10 18 3 8 20 2 7 -1
3
輸出樣例:have found! lchild:2 rchild:8
輸入樣例2:10 18 3 8 20 2 7 -1
8
輸出樣例2:have found! lchild:7 rchild:NULL
輸入樣例3:10 18 3 8 20 2 7 -1
5
輸出樣例3:NOT FOUND!
ACvoid BSTInsert(BSTree& T, BSTree s)
{
if (T == NULL)
T = s;
else if (s->data< T->data)
BSTInsert((T->lchild), s);
else
BSTInsert((T->rchild), s);
}
void BSTCreate(BSTree& T)
{
ElemType x; BSTree s;
T = NULL;
cin >>x;
while (x != -1)
{
s = new BSTNode;
s->data = x;
s->lchild = s->rchild = NULL;
BSTInsert(T, s);
cin >>x;
}
}
BSTree BSTSearch(BSTree T, ElemType k)
{
if (!T || T->data == k)
return T;
if (k< T->data)
return BSTSearch(T->lchild, k);
else
return BSTSearch(T->rchild, k);
}
你是否還在尋找穩(wěn)定的海外服務(wù)器提供商?創(chuàng)新互聯(lián)www.cdcxhl.cn海外機(jī)房具備T級流量清洗系統(tǒng)配攻擊溯源,準(zhǔn)確流量調(diào)度確保服務(wù)器高可用性,企業(yè)級服務(wù)器適合批量采購,新人活動首月15元起,快前往官網(wǎng)查看詳情吧
文章名稱:6-7數(shù)據(jù)結(jié)構(gòu)考題-二叉排序樹-創(chuàng)新互聯(lián)
URL鏈接:http://aaarwkj.com/article0/jddio.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站建設(shè)、ChatGPT、網(wǎng)站收錄、虛擬主機(jī)、靜態(tài)網(wǎng)站、網(wǎng)站排名
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容