二叉排序树的建立、查找、插入、删除

简介: 二叉排序树的建立、查找、插入、删除

如题,详情见下代码,基本类似于二叉树。

#include<iostream> 
using namespace std;
struct node{
  int data;
  node *lchild,*rchild;
};
void search(node* root,int x) { // 查找 
  if(root==NULL){  //没有查到 
    printf("fail!\n");
    return;
  }
  if(root->data==x){ //查到 
    printf("succeed!");
    return;
  }
  if(root->data>x)search(root->lchild,x);
  else search(root->rchild,x);
}
void insert(node* &root,int x){ //插入 
//要改变指针地址,所以引用 
  if(root==NULL){
    root=new node;
    root->data=x;
    root->lchild=root->rchild=NULL; 
    return;
  }
  if(root->data>x)insert(root->lchild,x);
  else insert(root->rchild,x);
}
node* creating(int a[],int n){  //创建二叉树 
  node* root=NULL;
  for(int i=0;i<n;i++)
  insert(root,a[i]);
  return root;  
}
void del(node* &root,int x){   //删除值为x的结点 
  if(root==NULL)return;    //查找不到 
  if(root->data==x){//查找到了,如果前面的search改为node*型这里就简单 
    node *pre,*p;
    pre=root;
    if(root->lchild==NULL&&root->rchild==NULL){
    //如果这个结点是叶子结点 ,直接删 
    root=NULL;return;}
    if(root->lchild!=NULL){ //如果结点有左子树,找前驱 
      p=root->lchild;
      while(p->rchild){
        pre=p;
        p=p->rchild;  
      }
      p->rchild=root->rchild;  
      //前驱p代替root位置,其左子树放在父亲 pre的右子树上 
      pre->rchild=p->lchild;
      p->lchild=root->lchild;
      delete(root);return;  
    }
    else{                   //结点只有右子树,找后继 
      p=root->rchild;
      while(p->lchild){
        pre=p;
        p=p->lchild;  
      }
      p->rchild=root->rchild;
      //后继p代替root位置,其右子树放在父亲 pre的左子树上 
      pre->lchild=p->rchild;
      p->lchild=root->lchild;
      delete(root);return;  
    }
  }
    if(root->data>x) 
  del(root->lchild,x);
  else del(root->rchild,x);
  }
void preorder(node* root){  //先序遍历,用来检测下结果 
  if(root==NULL)return;
  printf("%d",root->data);
  preorder(root->lchild);
  preorder(root->rchild);
}
int main() {
  int a[]={4,1,2,8,7,9};
  node* root=creating(a,6);
  insert(root,3);
  del(root,9);
  preorder(root);
  return 0;
}
相关文章
|
26天前
二叉树的创建、插入和删除
二叉树的创建、插入和删除
12 1
|
2月前
|
存储
单链表相关操作(插入,删除,查找)
单链表相关操作(插入,删除,查找)
28 4
|
2月前
|
算法 Java C++
实现二分查找树,支持插入、删除、查询操作。
实现二分查找树,支持插入、删除、查询操作。
27 0
|
11月前
|
存储 算法
数组算法:倒置,查找,插入,删除
数组算法:倒置,查找,插入,删除
72 0
链表学习(链表的创建,插入,删除,查找,遍历)
链表学习(链表的创建,插入,删除,查找,遍历)
103 0
|
算法
一天一个算法——>二叉搜索树的插入、查询、删除
一天一个算法——>二叉搜索树的插入、查询、删除
65 0
|
存储 C语言 C++
顺序表的插入、删除和查找(四)
详细介绍了数据结构中的顺序表
233 0
|
搜索推荐
查找-之二叉排序树(查找、插入、删除)
有序的线性表采用:折半/二分、插值、斐波那契查找相比顺序查找效率得到提高,但是在插入和删除时效率低(为维持数据的有序性) 在高效实现查找操作时,如何提高插入和删除的效率? 在一些应用场景:在查找时需要插入和删除
101 0
查找-之二叉排序树(查找、插入、删除)
二叉查找树的建立,插入,删除例程
二叉查找树的建立,插入,删除例程
|
算法
实验报告 线性表的基本操作及应用(单链表的创建,插入、删除、查找和打印算法)
实验报告 线性表的基本操作及应用(单链表的创建,插入、删除、查找和打印算法)
420 0
实验报告 线性表的基本操作及应用(单链表的创建,插入、删除、查找和打印算法)