/*------------tree insert use loop search-----------------------------*/
void insert_tree_loop(PTree _root, int value)
{
while(NULL !=_root)
{
if(value == _root->data)
{
return;
}
else if(value < _root->data)
{
if(NULL == _root->lchild)//find node insert new node
{
_root->lchild = create_node(value);//link now node left child node to new node
}
else//left tree is not null
{
_root = _root->lchild;
}
}
else
{
if(NULL == _root->rchild)//find node inset new node
{
_root->rchild = create_node(value);//link now node right child node to new node
}
else//right child tree is not null
{
_root = _root->rchild;
}
}
}
}
/*-------------------------------------------------------------------------------------------------*/
void delete_tree_loop(PTree _root, int value)
{
PTree parent=_root;
PTree temp = NULL;
if(_root==NULL || value==_root->data)
{
return;
}
while(_root)
{
if(value == _root->data)
{
break;
}
parent = _root;
if(value < root->data)
{
_root = _root->lchild;
}
else
{
_root = _root->rchild;
}
}
if(_root == NULL)
{
return;
}//can't find delete node
else
{
if(NULL == _root->lchild)
{
if(parent->lchild == _root)//注意条件
{
temp =_root;
parent->lchild = _root->rchild;
free(temp);
}
else
{
temp = _root;
parent->rchild = _root->rchild;
free(temp);
}
}//left child tree is non,or neither
else if(NULL == _root->rchild)
{
if(parent->lchild == _root)
{
temp = _root;
parent->lchild = _root->lchild;
free(temp);
}
else
{
temp = _root;
parent->rchild = _root->lchild;
free(temp);
}
}//right child tree is non,or neither
else
{
parent = _root;
temp = _root->lchild;
while(temp)
{
parent = temp;
temp = temp->rchild;
}
_root->data = temp->data;
if(parent == _root)
{
parent->lchild = temp->lchild;
}
else
{
parent->rchild = temp->lchild;
}
free(temp);
}
}
}
浙公网安备 33010602011771号