插入及建立
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);
}
node* Create(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->rchild != NULL)
{
root = root->rchild;
}
return root;
}
node* findMin(node* root)
{
while(root->lchild != NULL)
{
root = root->lchild;
}
return root;
}
void deleteNode(node* &root, int x)
{
if(root == NULL) return;
if(root == x)
{
if(root->lchild == NULL && root->rchild == NULL) root = NULL;
else if(root->lchild != NULL){
node* pre = findMax(root->lchild);
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);
}
对二叉查找树进行中序遍历,遍历的结果是有序的。