搜索二叉树

来源:互联网 发布:sn ty gm js是什么 编辑:程序博客网 时间:2024/05/19 04:26
 
#include <iostream>#include <cstdio>#include <cstdlib>using namespace  std;typedef struct BiThrNode{   int data;struct BiThrNode *lchild, *rchild;}BiThrNode,*BiThrTree;void Insert_Tree(BiThrTree &T,int e){  if(!T){BiThrTree t = (BiThrTree)malloc(sizeof(BiThrNode));    t->data = e;t->lchild = t->rchild = NULL;T =  t;}     else if(e<T->data){      Insert_Tree(T->lchild,e);    }    else if(e>T->data){      Insert_Tree(T->rchild,e);    }    else{}}int length(BiThrTree t){if(t){return (length(t->lchild)+length(t->rchild)+1);}}bool Delete_Tree(BiThrTree &t,int &e){ if(t){if(t->data == e){  BiThrTree item = t;if(!t->lchild){                    //左空,右孩子连上 t = t->rchild;                 free(item);   return true;}if(!t->rchild){                 //右空,左孩子连上    t = t->lchild;     free(item);    return true;}    if(t->lchild&&t->rchild){             //左右非空       if(!(t->lchild->rchild)){        //左子树右节点为空            t->data= t->lchild->data;   //把待删除节点的双支节点的中序前件(t->lchild->data)的节点值赋给待删除节点            return  Delete_Tree(t->lchild,t->lchild->data);    //删除双支节点的中序前件节点(这里其实包含了将序前件节点的左孩子                                                  //连同子树连接到中序前件节点位置                                                      }       else{            BiThrTree p1 = t,p2 = t->lchild;       while(p2->rchild){  //循环左孩子的找到其最右节点            p1 = p2; p2 = p2->rchild;}               t->data =  p2->data;           return  Delete_Tree(p1->rchild,p2->data);     }          }    }    else if(e<t->data){return  Delete_Tree(t->lchild,e);     }else{    return  Delete_Tree(t->rchild,e);    }}    return false;}void MId_Queue(BiThrTree T){if(T){MId_Queue(T->lchild);printf("%d ",T->data);MId_Queue(T->rchild);}}int main(int argc, char** argv) {    BiThrTree T = NULL;  //初始化     int a;    printf("输入数据以-1结束\n");    scanf("%d",&a);    while(true){    if(a!=-1){    Insert_Tree(T,a);}    else{    break;}scanf("%d",&a);}int k1 = printf("%d\n",length(T));printf("中序遍历为:");MId_Queue(T);printf("\n");printf("请输入你要删除的数:\n");int num;scanf("%d",&num);bool s = Delete_Tree(T,num);    if(s){    printf("%d_删除成功\n",num); }    else{    printf("%d_删除失败\n",num);}    printf("中序遍历为:");MId_Queue(T);printf("\n");/* t = p->right;   p->right = t->left;   t->left = p;   p = t;*/return 0;}

原创粉丝点击