#include <cstdlib>
#include <iostream>
#define N 10 
using namespace std;
typedef struct node *link;
struct node {
       int item;
       link l,r;
       };
link NODE(int item,link l,link r)
{
 link t = (link)malloc(sizeof(struct node));
 t->item = item;
 t->l = l;
 t->r = r;
 return t;      
}
link insert_node(link t,int item)
{
  if(t == NULL) return NODE(item,NULL,NULL);
  if(item < t->item)
	  t->l = insert_node(t->l,item);
  else
	  t->r = insert_node(t->r,item);
  return t;
}
//中序打印
void inOrder(link root){
if(root){
 inOrder(root->l);
 cout<<root->item<<"  ";
 inOrder(root->r);

         }
}
link bst_remove(link t,int item)
{
  if(t == NULL) return NULL; //没找到,不做操作
  if(item < t->item)//小于,向左找
          t->l = bst_remove(t->l,item);
   else if(item > t->item)//大于。向右找 
          t->r = bst_remove(t->r,item);
   else  {//等于,做操作
    link x;
          if(t->l){//左子树不为空,在左子树取最大值替换当前需要删除的点 
                  for(x = t->l;x->r;x= x->r){;}//最大值在右边,x指向最大的节点(叶节点)
                   t->item = x->item; //把x拿上去;
                   t->l = bst_remove(t->l,t->item); 
                   }
            else if(t->r){//左子树为空。 
                 for(x = t->r;x->l;x = x->l){;}//最小值在左边 ,x指向最小的节点(叶节点) 
                 t->item = x->item;//把x拿上去 
                 t->r = bst_remove(t->r,t->item);
                  }
            else{//既没有左子树,又没有右子树,直接删除
            free(t);
            t = NULL;             
                 }      
         }  
     return t;//t为树的根节点 
}
int main(int argc, char *argv[])
{
    srand(time(NULL));
    link root = NULL;
    int a[] = {1,40,20,11,9,5,17,18,88,29};
    for(int i =0;i<N;i++)
    {
            root = insert_node(root,a[i]);
     }
    
    inOrder(root);
    cout<<endl;
    root = bst_remove(root ,18);
    inOrder(root);
    system("PAUSE");
    return EXIT_SUCCESS;
}


 

 

 

 

BST树_子树