1、查找
void search(Node* root,int x)
{
if(root==NULL)
{
printf("search failed\n");
return;
}
if(x==root->data)
{
printf("%d\n",root->data);
}
else if(x<root->data)
{
search(root->lchild,x);
}
else
{
search(root->rchild,x);
}
}
2、插入
void insert(Node* &root,int x)
{
if(root==NULL)
{
root=newNode(x);
return;
}
if(x==root->data)
{
return;
}
else if(x<root->data)
{
insert(root->lchild,x);
}
else
{
insert(root->rchild,x);
}
}
3、创建
Node* create(int data[],int n)
{
Node* root=NULL;
for(int i=0;i<n;i++)
{
insert(root,data[i]);
}
return root;
}
4、寻找以root为根的树中,最大权值的结点
Node* findMax(Node* root)
{
while(root->rchild!=NULL)
{
root=root->rchild;
}
return root;
}
5、寻找以root为根的树中,最小权值的结点
Node* findMin(Node* root)
{
while(root->lchild!=NULL)
{
root=root->lchild;
}
return root;
}
6、 删除以root为根结点的树中,权值为x的结点
void deleteNode(Node* &root,int x)
{
if(root==NULL) return;
if(root->data==x)
{
if(root->lchild==NULL&&root->rchild==NULL)
{
root=NULL; //将root指针置为空,这样,其父节点对应的孩子指针域便置为空了
}
else if(root->lchild!=NULL)
{
Node* pre=findMax(root->lchild); //root前驱
root->data=pre->data;
deleteNode(root->lchild,pre->data);
}
else
{
Node* next=findMin(root->rchild);
root->data=next->data;
deleteNode(root->rchild,next->data);
}
}
else if(root->data>x)
{
deleteNode(root->lchild,x);
}
else
{
deleteNode(root->rchild,x);
}
}