struct node{
typename data;
node* lchild;
node* rchild;
};
node* newNode(int v){
node* Node = new node;
Node->data = v;
Node->lchild = Node->rchild = NULL;
return Node;
}
/*查找*/
void searchBST(node* root, int x)
{
if(root == NULL){
printf("search failed\n");
return 0;
}
if(root->data==x)
printf("%d\n",root->data);
else if(root->data>x)
search(root->lchild, x);
else
search(root->rchild, x);
}
/*插入*/
void insertBST(node* &root, int x)//& is very important.Cuz after insertation
{
if(root == NULL){
root = newNode(x);
return;
}
if(x == root->data)
return;
else if(x < root->data)
insertBST(root->lchild, x);
else
insertBST(root->rchild, x);
}
/*建立*/
node* Create(int data[], int n)
{
node* root = NULL;
for(int i=0;i<n;i++)
insertBST(root, data[i]);
return root;
}
/*前驱*/
node* findMax(node* root)
{
while(root->rchild!=NULL)
root = root->rchild;
return root;
}
/*后继*/
node* findMin(node* root)
{
while(root->lchild!=NULL)
root = root->lchild;
return root;
}
/*删除*/
void deleteBST(node* &root, int x)
{
if(root == NULL)
return;
if(root->data == x)
{
if(root->lchild == NULL && root->rchild == NULL)
root = NULL;
else if(root->lchild!=NULL)
{
node* pre = findMax(root->lchild);
root->data = pre->data;
deleteBST(root->lchild, root->data);
}
else
{
node* next = findMin(root->rchild);
root->data = next->data;
deleteBST(root->rchild, root->data);
}
}
else if(root->data > x)
deleteBST(root->lchild, x);
else
deleteBST(root->rchild, x);
}
BST 基操
最新推荐文章于 2023-08-30 11:17:39 发布