二进制搜索树插入有问题,左树工作正常,但右树工作不正常

时间:2019-11-02 14:42:09

标签: tree binary-tree binary-search-tree insertion perl-data-structures

  

这是我正在使用的插入函数。作为左孩子的根创建和插入工作正常,但是作为右孩子的插入仅发生两次。

struct node * insert(struct node *root1, struct node *new1)
{    printf("root address=%u",root1);

    if(root1==NULL){
            printf("xyz");
        root1=new1;
    return root1;
    }
  if(root1->data>new1->data)
    {
        if(root1->lchild==NULL){
            root1->lchild=new1;
            printf("A1");
        }
        else{
                printf("A2");
            insert(root1->lchild,new1);

        }

    }
    if(root1->data < new1->data)
    {
        if(root1->rchlid==NULL){
            root1->rchlid=new1;
            printf("B1");
        }
        else{
                printf("B2");
          insert(root1->rchlid,new1);

        }

    }
    printf("FFF");
  return root;
}

1 个答案:

答案 0 :(得分:0)

简体:


struct node * insert(struct node *zroot, struct node *new1)
{    
    if(zroot==NULL) return new1;

    if (zroot->data>new1->data) zroot->lchild = insert(zroot->lchild,new1);
    else zroot->rchild = insert(zroot->rchild,new1);

    return zroot;
}