【问题描述】
请根据输入的数据创建一棵二叉排序树。然后执行相应操作。
1 删除某一值为x的结点
2 求指定结点y在二叉排序树中的层数
【输入形式】
结点数据,以0代表结束输入。
待删除的x,待求层数的y
【输出形式】
创建好的二叉排序树的拓展的前序遍历结果
删除后的二叉排序树的中序遍历结果
y所在的层数
【样例输入】
29 39 15 25 28 10 11 2 0
10
11
【样例输出】
29 15 10 2 # # 11 # # 25 # 28 # # 39 # #
2 11 15 25 28 29 39
4
【样例说明】
若待删除的结点包含左右子树,则以其左子树的最右结点代替它。
#include<bits/stdc++.h>
using namespace std;
int depth=0;
typedef struct BiNode
{
int date;
BiNode*LChild;
BiNode*RChild;
}*BiTree;
void insert_BST(BiTree root,int v)
{
BiNode*p=root;
BiNode*f=NULL;
while(p!=NULL)
{
f=p;
if(v<p->date) p=p->LChild;
else p=p->RChild;
}
BiNode*temp=new BiNode;
temp->date=v;
temp->LChild=NULL;
temp->RChild=NULL;
if(v<f->date) f->LChild=temp;
else f->RChild=temp;
}
void create_BST(BiTree root)
{
int first;cin>>first;//****/
if(first!=0) {root->date=first;root->LChild=NULL;root->RChild=NULL;}
else return;
while(1)
{
int v;cin>>v;
if(v!=0) insert_BST(root,v);
else break;
}
}
void preOrder(BiTree root)
{
if(root!=NULL)
{
cout<<root->date<<" ";
preOrder(root->LChild);
preOrder(root->RChild);
}
else cout<<"# ";
}
void inOrder(BiTree root)
{
if(root!=NULL)
{
inOrder(root->LChild);
cout<<root->date<<" ";
inOrder(root->RChild);
}
}
void get_depth(BiTree root,int v)
{
BiNode*p=root;
while(p->date!=v)
{
depth++;
if(v<p->date) p=p->LChild;
else p=p->RChild;
}
depth++;
}
void del(BiTree &root,int v)
{
//找到v的位置
BiNode*p=root;
BiNode*f=NULL;
while(p->date!=v)
{
f=p;
if(v<p->date) p=p->LChild;
else p=p->RChild;
}
//v为叶子节点
if(p->LChild==NULL&&p->RChild==NULL)
{
if(f->LChild==p) f->LChild=NULL;
else f->RChild=NULL;
}
//v只有右子树
else if(p->LChild==NULL&&p->RChild!=NULL)
{
if(f==NULL)
{
root=p->RChild;
}
else
{
if(f->LChild==p) f->LChild=p->RChild;
else f->RChild=p->RChild;
}
}
//v只有左子树
else if(p->LChild!=NULL&&p->RChild==NULL)
{
if(f==NULL)
{
root=p->LChild;
}
else
{
if(f->LChild==p) f->LChild=p->LChild;
else f->RChild=p->LChild;
}
}
//v左右子树都有(找到v左子树的最右节点rear)
else
{
BiNode*q=p;//rear的前驱指针
BiNode*rear=p->LChild;
while(rear->RChild!=NULL)
{
q=rear;
rear=rear->RChild;
}
p->date=rear->date;
if(q->LChild==rear) q->LChild=rear->LChild;
else q->RChild=rear->LChild;
}
}
int main()
{
BiTree bst=new BiNode;
create_BST(bst);
int v,y;//待删除的节点和求层数的节点
cin>>v>>y;
preOrder(bst);
cout<<endl;
del(bst,v);
get_depth(bst,y);
inOrder(bst);
cout<<endl;
cout<<depth<<endl;
return 0;
}