【问题标题】:Having problem with Binary Search Tree insertion,It is working fine for left tree but not for right二叉搜索树插入有问题,左树工作正常,右树不行
【发布时间】:2020-02-28 12:17:36
【问题描述】:

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

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;
}

【问题讨论】:

  • 使用返回值,卢克!
  • 先生在哪里使用
  • 另外:root1 != root(从未定义过根)

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


【解决方案1】:

简化:


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;
}

【讨论】:

  • 先生,我已使用此代码,但问题仍然存在。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-11-02
  • 1970-01-01
  • 1970-01-01
  • 2019-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多