typedef
int bsdatatype;
typedef
struct bstreenode
bstreenode,
*pbstreenode;
pbstreenode bsbuynode
(bsdatatype d)
newnode->data = d;
newnode->pleft =
null
; newnode->pright =
null
;return newnode;
}
void
initbstree
(pbstreenode* bstree)
pbstreenode findbstree
(pbstreenode bstree, bsdatatype d)
return
null
;}
pbstreenode findbstreenor
(pbstreenode bstree, bsdatatype d)
else
if(bstree->data == d)
//相等
else
if(bstree->data > d)
//左子樹
else
//右子樹
}
void
insertbstree
(pbstreenode* bstree, bsdatatype d)
else
//樹不為空
//插入結點
cur =
bsbuynode
(d);
if(parent->data > d)
//插入到左孩子
parent->pleft = cur;
else
//插入到右孩子
parent->pright = cur;
}}
void
insertbstreenor
(pbstreenode* bstree, bsdatatype d)
elseif(
(*bstree)
->data > d)
//插入到左子樹
elseif(
(*bstree)
->data < d)
//插入到右子樹
else
//相等
}
void
deletebstree
(pbstreenode* bstree, bsdatatype d)
//查詢刪除的位置
pbstreenode cur =
*bstree;
pbstreenode parent = cur;
while
(d != cur->data)if(
null
== cur)
//找不到
return
;//刪除結點cur
//pbstreenode del = cur; //釋放空間if(
(null
== cur->pleft &&
null
!= cur->pright)||(
null
== cur->pleft &&
null
== cur->pright)
)//只有右孩子或左右孩子不存在
else
//cur不是根結點
}elseif(
null
!= cur->pleft &&
null
== cur->pright)
//只有左孩子
else
//cur不是根結點
}elseif(
null
!= cur->pleft &&
null
!= cur->pright)
//左右孩子存在
//交換cur與str的值
cur->data = str->data;
//刪除替代結點
if(str == parent->pleft)
//str為雙親的左子樹
parent->pleft = str->pleft;
//把str的左子樹作為雙親的左子樹
else
//cur為雙親的右子樹
parent->pright = str->pright;
//把str的左子樹作為雙親的右子樹
cur = str;
}free
(cur)
; cur =
null
;}
int
deletebstreenor
(pbstreenode* bstree, bsdatatype d)
if(d <
(*bstree)
->data)
return
deletebstreenor(&
((*bstree)
->pleft)
, d)
;//進入左子樹
else
if(d >
(*bstree)
->data)
return
deletebstreenor(&
((*bstree)
->pright)
, d)
;//進入右子樹
else
elseif(
null
== del->pright)
//只有左孩子
else
//左右孩子均存在
del->data = pcur->data;
//替換
return
deletebstreenor(&
((*bstree)
->pright)
, del->data)
;//刪除該節點右子樹中的最左端的結點}}
}
void
destroybstree
(pbstreenode* bstree)
}
二叉搜尋樹的基本操作
建立乙個非負二叉搜尋樹 1表空結點 編寫查詢函式,層序遍歷函式,插入函式,刪除函式,查詢最大值最小值函式 輸入該樹和要查詢的值 輸出 如果找到,列印出 x is found 沒找到列印出 not found 列印出層序遍歷序列 刪除最大值和最小值 刪除成功輸出 x is delete 最後再進行一層...
二叉搜尋樹的基本操作
二叉搜尋樹 binary search tree 它或者是一棵空樹,或者是具有下列性質的二叉樹 若它的左子樹不空,則左子樹上所有結點的值均小於它的根結點的值 若它的右子樹不空,則右子樹上所有結點的值均大於它的根結點的值 它的左 右子樹也分別為二叉搜尋樹樹。節點設定 typedef int datat...
二叉搜尋樹的基本操作
pragma once typedef int datatype typedef struct bstreenode bstnode include include include bstnode buybstreenode datatype data pnewnode data data pnew...