二叉搜索树

初始化

void SearchTreeInit(SearchNode** pRoot){
  if(pRoot == NULL){
     return;
  }
  *pRoot = NULL;
  return;
}

销毁

void DestroySearchNode(SearchNode* node){
  free(node);
}

void SearchTreeDestroy(SearchNode** pRoot){
  if(pRoot == NULL){
    return;
  }
  if(*pRoot == NULL){
    return;
  }
  SearchNode* root = *pRoot;
  SearchTreeDestroy(&root->lchild);
  SearchTreeDestroy(&root->rchild);
  DestroySearchNode(root);
  *pRoot = NULL;
  return;
}

插入

void SearchTreeInsert(SearchNode** pRoot,SearchNodeType to_insert){
  if(pRoot == NULL){
    return;
  }
  if(*pRoot == NULL){
   SearchNode* new_node = CreateSearchNode(to_insert);
   *pRoot = new_node;
   return;
  }
  SearchNode* cur = *pRoot;
  if(to_insert < cur->data){
    SearchTreeInsert(&cur->lchild, to_insert);
  }else if(to_insert > cur->data){
     SearchTreeInsert(&cur->rchild,to_insert);
   }else{
      return;
    }
  return;
}

找节点

SearchNode* SearchTreeFind(SearchNode* root,SearchNodeType to_find){
  if(root == NULL){
    return NULL;
  }
  if(to_find < root->data){
    return SearchTreeFind(root->lchild, to_find);
  }
  else if(to_find > root->data){
    return SearchTreeFind(root->rchild,to_find);
  }else{
     return root;
   }
}

删除(思路):

1.找到to_remove所在的位置

2.如果没找到,就直接返回

3.如果找到了,分情况讨论

  a.要删除的节点没有子树

  b.要删除的节点只有左子树

  c.要删除的节点只有右子树

  d.要删除的节点有左右子树

void SearchTreeRemove(SearchNode** pRoot, SearchNodeType to_remove){
  if(pRoot == NULL){
    return;
  }
  if(*pRoot == NULL){
   //2.
    return;
  }
//1.
  SearchNode* root = *pRoot;
  if(to_remove < root->data){
    SearchTreeRemove(&root->lchild,to_remove);
    return;
  }else if(to_remove > root->data){
    SearchTreeRemove(&root->rchild,to_remove);
    return;
   }else{
SearchNode* to_remove_node = root;
//3.
     if(root->lchild == NULL && root->rchild == NULL){
      //a.
       *pRoot = NULL;
        DestroySearchNode(root);
        return;
     }else if(root->lchild != NULL && root->rchild == NULL){
       //b. 
       *pRoot = to_remove_node->lchild;
       DestroySearchNode(to_remove_node);
       return;
     }else if(root->lchild == NULL && root->rchild != NULL){
       //c
 *pRoot = to_remove_node->rchild;
       DestroySearchNode(to_remove_node);
       return;
     }else{
        //d.
       SearchNode* min = to_remove_node->rchild;
       while(min->lchild != NULL){
         min = min->lchild;
       }
       to_remove_node->data = min->data;
       SearchTreeRemove(&to_remove_node->rchild, min->data);
       return;
     }
   }
  return;
}

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页