Friday, March 21, 2014

BST insert + delete

1. BST insert:
BTNode* insertNode(BTNode *root, int insval){
if(!root){
root=new BTNode(insval);
return root;
}

BTNode *p==root;
BTNode *cur==root;

while(cur!=NULL){
if(insval<cur->value){
p=cur;
cur=cur->left;
}
else if(insval>cur->val){
p=cur;
cur=cur->right;
}
else{
cout<<"Have exsited."<<endl;
return cur;
}
}
if(insval< p->value){
cur=new BTNode(insval);
p->left= cur;
}
else if(insval > p->val){
cur=new BTNode(insval);
p->right= cur;
}
return cur;
}

/****************************************************************************/
2. BST search, return parent.
BTNode* search(BTNode *root, int insval, &position){
if(!root) return NULL;

BTNode *p==root;
BTNode *cur==root;
    position=0;

while(cur!=NULL){
if(insval<cur->value){
p=cur;
cur=cur->left;
position=-1;
}
else if(insval>cur->val){
p=cur;
cur=cur->right;
position=1;
}
else{
cout<<"Find it."<<endl;
return p;
}
}

/******************************************************************/
3. BST delete.
BTNode* deleteNode(BTNode *root){
 ///////
 parent = search(root, node, &position);    //get parent pointer.

 if(parent == NULL)     //该节点不在二叉树中
  return root;
 else{
  switch(position){
  case -1: point = parent->left; //左子树节点
   break;
  case 1:  point = parent->right; //右子树节点
   break;
  case 0: point = parent;   //根节点
   break;
  }

//case1: 没有左子树也没有右子树
 if(point->left==NULL && point->right==NULL){
   switch(position){   //判断删除的位置
   case -1: parent->left = NULL;
    break;
   case 1: parent->right = NULL;
    break;
   case 0: parent = NULL;
    break;
   }
   free(point);
   return root;
 }
 
  //case2: 没有左子树
  if(!point->left && point->right){
   if(parent!=point)    //!!!!!!!!!!
 
    parent->right = point->right;//
   else  //
    root = root->right;    //将根节点指向右子节点!!!!!!!!!!!
   free(point);      //释放节点内存
   return root;
  }

  //case3: 没有右子树
  else if(point->right==NULL && point->left!=NULL){
   if(parent != point)
 
    parent->left = point->left;
   else
    root = root->left;     //将根节点指向左子树节点
   free(point);
   return root;
  }

  //case4: 有左子树也有右子树
  else if(point->right!=NULL && point->left!=NULL){
   parent = point;    
   child = point->left;    //设置子节点
 
   while(child->right != NULL){
    parent = child;  
    child = child->right;
   }

   //*******************************//
   point->data = child->data; //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!左子数最大值替换删除点值

   if(parent->left == child)
    parent->left = child->left;
   else
    parent->right = child->right;
   free(child);
   return root;       //返回根节点的指针
  }

No comments:

Post a Comment