- #include"iostream"
- using
namespace std; -
- struct
BiTNode - {
-
int data; -
struct BiTNode *lchild,*rchild; - };
- typedef
struct BiTNode BiTNode,*biTree; -
-
- biTree
SearchBST(biTree T,int key) - {
-
//在根指针T所指的二叉排序树中递归地查找某关键字等于key的数据元素 -
//若查找成功,则返回指向数据元素节点的指针,否则,返回空指针 -
if (T==NULL) -
{ -
return NULL; -
} -
else -
{ -
if (key==T->data) -
{ -
return T; -
} -
else if (key<T->data) -
{ -
return (SearchBST(T->lchild,key)); -
} -
else -
{ -
return(SearchBST(T->rchild,key)); -
} -
} -
- }
-
-
- void
InsertBST (biTree &T , int key) - {
-
-
-
if (T==NULL) -
{ -
biTree x; -
x=new BiTNode; -
x->data=key; -
x->lchild=x->rchild=NULL; -
T=x; -
cout<<"插入成功\n"; -
} -
else -
{ -
if (T->data==key) -
{ -
cout<<"节点已存在\n"<<endl; -
} -
else if (key<T->data) -
{ -
InsertBST(T->lchild,key); -
} -
else -
{ -
InsertBST(T->rchild,key); -
} -
} -
- }
-
- biTree
CreateTree() - {
-
biTree T=NULL; -
int num=0; -
cout<<"请输入一次插入的值:"; -
cin>>num; -
while (num!=-1) -
{ -
InsertBST(T,num); -
cout<<"下一个插入的值(-1结束):"; -
cin>>num; -
} -
cout<<"二叉树建立完成\n"; -
return T; - }
-
- int
dele(biTree &p) - {
-
biTree q,s; -
if (p->lchild==NULL) -
{ -
q=p; -
p=p->lchild; -
delete q; -
} -
else if (p->rchild==NULL) -
{ -
q=p; -
p=p->rchild; -
delete q; -
} -
else -
{ -
q=p; -
s=p->lchild; -
while(s->rchild) -
{ -
q=s; -
s=s->rchild; -
} -
p->data=s->data; -
if (q!=p) -
{ -
q->rchild=s->lchild; -
} -
else -
{ -
q->lchild=s->lchild; -
} -
delete s; -
-
} -
return 1; -
- }
- int
deleteBTree(biTree &T,int num) - {
-
if (T==NULL) -
{ -
return 0; -
} -
else -
{ -
if (num==T->data) -
{ -
return dele(T); -
} -
else if (num<T->data) -
{ -
return deleteBTree(T->lchild,num); -
} -
else -
{ -
return deleteBTree(T->rchild,num); -
} -
-
} - }
- void
middVisit(biTree T) - {
-
if (T==NULL) -
{ -
; -
} -
else -
{ -
middVisit(T->lchild); -
cout<<T->data<<" , "; -
middVisit(T->rchild); -
} -
- }
- void
firstVisit(biTree T) - {
-
if (T==NULL) -
{ -
; -
} -
else -
{ -
cout<<T->data<<" , "; -
firstVisit(T->lchild); -
firstVisit(T->rchild); -
} - }
- void
lastVisit(biTree T) - {
-
if (T==NULL) -
{ -
; -
} -
else -
{ -
-
lastVisit(T->lchild); -
lastVisit(T->rchild); -
cout<<T->data<<" , "; -
} - }
- int
main() - {
-
biTree T=CreateTree(); -
cout<<"中序遍历结果:\n"; -
middVisit(T); -
cout<<endl; -
cout<<"前序遍历结果:\n"; -
firstVisit(T); -
cout<<endl; -
cout<<"后序遍历结果:\n"; -
lastVisit(T); -
cout<<endl; -
-
deleteBTree(T,7); -
cout<<"中序遍历结果:\n"; -
middVisit(T); -
cout<<endl; -
return 0; - }
<script type="text/javascript" id="wumiiRelatedItems"> </script>