二叉搜索树
#include <iostream>
using namespace std;
struct node
{
int data;
node *lchild;
node *rchild;
};
node *create(int v)
{
node *Node = new node;
Node->data = v;
Node->lchild = NULL;
Node->rchild = NULL;
return Node;
}
void search(node *root, int x)
{
if (root == NULL)
{
return;
}
if (root->data == x)
{
cout << root->data << endl;
}
else if (root->data > x)
{
search(root->lchild, x);
}
else
{
search(root->rchild, x);
}
}
void insert(node *&root, int x)
{
if (root == NULL)
{
root = create(x);
return;
}
if (root->data == x)
{
return;
}
else if (root->data > x)
{
insert(root->lchild, x);
}
else
{
insert(root->rchild, x);
}
}
node *build(int data[], int n)
{
node *root = NULL;
for (int i = 0; i < n; i++)
{
insert(root, data[i]);
}
return root;
}
node *findMax(node *root)
{
while (root->lchild)
{
root = root->lchild;
}
return root;
}
node *findMin(node *root)
{
while (root->rchild)
{
root = root->rchild;
}
return root;
}
void deleteNode(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){
node* temp = findMax(root->lchild);
root->data = temp->data;
deleteNode(root->lchild,temp->data);
}else{
node *temp = findMin(root->rchild);
root->data = temp->data;
deleteNode(root->rchild, temp->data);
}
}else if(root->data > x){
deleteNode(root->lchild,x);
}else{
deleteNode(root->rchild,x);
}
}