如何在不使用临时节点的情况下为根添加值?

时间:2019-06-17 21:18:49

标签: c pointers binary-search-tree

我正在尝试创建一个向BST添加节点的功能。

插入功能的代码如下。

void insert(struct node **root,int data){
    if(!(*root)){
        struct node *temp=(struct node*)malloc(sizeof(struct node));
        temp->data=data; //how to do without temp node
        temp->left=temp->right=NULL;
        *root=temp;
        return;
    }

    if(data<(*root)->data){
        insert(&(*root)->left,data);
    }
    else if(data>(*root)->data){
        insert(&(*root)->right,data);
    }
}

如何在不使用临时节点的情况下为第一个if条件插入值。我对指针还很陌生。我能够得到正确的答案,但想避免使用临时节点

编辑:

这是根据@ 1201ProgramAlarm的建议 按照这个我在打印时没有任何输出

struct node{
    int data;
    struct node *left,*right;
};
//
void print_inorder(struct node * tree)
{
    if (tree)
    {
        print_inorder(tree->left);
        printf("%d\n",tree->data);
        print_inorder(tree->right);
    }
}
void insert(struct node **root,int data){
    if(!(*root)){
        struct node *temp=(struct node*)malloc(sizeof(struct node));
        (*root)->data=data;
        (*root)->left=(*root)->right=NULL;
        return;
    }

    if(data<(*root)->data){
        insert(&(*root)->left,data);
    }
    else if(data>(*root)->data){
        insert(&(*root)->right,data);
    }
}

void main(){

    struct node *root=(struct node*)malloc(sizeof(struct node));
    root=NULL;
    insert(&root,9);
    insert(&root,4);
    insert(&root,15);
    insert(&root,6);
    insert(&root,12);
    insert(&root,17);
    insert(&root,2);
    print_inorder(root);
}

编辑2:在函数中删除临时初始化,并在main中将根初始化为null。

void insert(struct node **root,int data){
    if(!(*root)){
        (*root)->data=data;
        (*root)->left=(*root)->right=NULL;
        return;
    }

    if(data<(*root)->data){
        insert(&(*root)->left,data);
    }
    else if(data>(*root)->data){
        insert(&(*root)->right,data);
    }
}

void main(){
    struct node *root=NULL;
    insert(&root,9);
    insert(&root,4);
    insert(&root,15);
    insert(&root,6);
    insert(&root,12);
    insert(&root,17);
    insert(&root,2);
    printf("Inorder Traversal\n");
    print_inorder(root);
}

仍然无法正常工作。对指针的帮助是非常新颖的。

0 个答案:

没有答案