二叉查找树是中已经排好序的二叉树,也称二插排序树
二叉查找树的插入
void insertTree(node*& tree,char elem) //递归插入
{
if (!tree)
{
tree=(node*)malloc(sizeof(node));
tree->data=elem;
tree->lchild=NULL;
tree->rchild=NULL;
}
else
{
if(elem<tree->data)
insertTree(tree->lchild,elem);
else
insertTree(tree->rchild,elem);
}
}
void insertTree1(node*& tree,char elem) //非递归插入
{
node* t=(node*)malloc(sizeof(node));
t->data=elem;
t->lchild=NULL;
t->rchild=NULL;
if (!tree)
{
tree=t;
return;
}
node* current=tree;
node* parent=tree;
while (current)
{
if (elem<current->data)
{
parent=current;
current=current->lchild;
}
else
{
parent=current;
current=current->rchild;
}
}
if (elem<parent->data)
parent->lchild=t;
else
parent->rchild=t;
}
删除二叉查找树节点(未考虑删除节点在叶子节点的情况)
void deleteTree(node*& tree,char elem)
{
node* current=searchTree(tree,elem);
node* parent=NULL;
node* t=current; //记录删除节点位置
while(current->lchild||current->rchild)
{
if(current->lchild) //左子结点的最大值
{
parent=current;
current=current->lchild;
while (current->rchild)
{
parent=current;
current=current->rchild;
}
}
else if(current->rchild) //右子结点的最小值
{
parent=current;
current=current->rchild;
while (current->lchild)
{
parent=current;
current=current->lchild;
}
}
swap(current->data,t->data); //交换删除节点数据
t=current; //修改删除节点位置
}
if (parent->lchild==current)
parent->lchild=NULL;
else if (parent->rchild==current)
parent->rchild=NULL;
free(current);
current=NULL;
}