1)輸入數列L 生成一棵二叉排序T
2)對二叉排序樹T作中序遍歷 輸出結果
3)輸入元素x 查找二叉排序樹T 若存在含x的結點 則洗掉該結點 并作中序遍歷(執行操作2) 否則輸出資訊“無x”
uj5u.com熱心網友回復:
#include <iostream>using namespace std;
class node
{
public:
node(int i):data(i),left(NULL),right(NULL){}
void inorder(node *&root) //中序遍歷,符合升序輸出
{
if(root!=NULL)
{
inorder(root->left);
cout<<root->data<<' ';
inorder(root->right);
}
}
void insert(node *&ptr,int item) //在查找樹中插入元素
{
if(ptr==NULL)
ptr=new node(item);
else if(item<ptr->data)
insert(ptr->left,item);
else insert(ptr->right,item);
}
node *find(node *&ptr,int item) //在查找樹中查找元素,找到回傳所在結點指標,找不到回傳空指標。
{
if(ptr==NULL)
return NULL;
if(ptr->data=https://bbs.csdn.net/topics/=item)
return ptr;
else if(item<ptr->data)
find(ptr->left,item);
else find(ptr->right,item);
}
node *&findy(node *&ptr,int item) //在查找樹中查找肯定存在的元素,并回傳其參考
{
if(ptr->data=https://bbs.csdn.net/topics/=item)
return ptr;
else if(item<ptr->data)
findy(ptr->left,item);
else findy(ptr->right,item);
}
node* rl(){return left;}
node* rr(){return right;}
void dele(node *&ptr) //洗掉值為item所在結點
{
if(ptr->rl()==NULL&&ptr->rr()==NULL)
ptr=NULL;
else if(ptr->rr()==NULL)
ptr=ptr->rl();
else
ptr=ptr->rr();
}
private:
int data;
node *left; //左孩子結點
node *right; //右孩子結點
};
int main()
{
int t,i=0,j;
cout<<"輸入數字個數(結點個數):";
cin>>t;
cout<<"輸入"<<t<<"個數字,數字之間用空格隔開:";
cin>>j;
node *x=new node(j);
for(;i<t-1;i++)
{
cin>>j;
x->insert(x,j);
}
cout<<"中序遍歷為:";
x->inorder(x); //作中序遍歷
cout<<"\n輸入操作(當輸入-1時程式結束):"<<endl;
cin>>j;
while(j!=-1)
{
node *t=x->find(x,j); //定位結點
if(t!=NULL)
{
node *&y=x->findy(x,j);
x->dele(y);
cout<<"中序遍歷為:";
x->inorder(x);
}
else cout<<"無"<<j;
cout<<"\n輸入操作(當輸入-1時程式結束):"<<endl;
cin>>j;
}
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/94392.html
標籤:基礎類
上一篇:時光飛逝,10前BCB版的JSP季世平等牛人現在何處?
下一篇:注冊表中明明有一個欄位值,但是RegEnumValue 沒有檢測出來,直接回傳ERROR_NO_MORE_ITEMS,回傳值是259,為什么!!!!
