如何在二叉搜索树中插入新节点?

问题描述 投票:0回答:2

我试图插入BST N次,并且必须要求用户在insert函数内输入数据。这是我的代码。我试图使用预订方法打印树,但它仅打印最后的输入。我必须使用ID作为密钥,并使用PreOrder打印所有数据Salary和ID。


    #include <stdio.h>
    #include <stdlib.h>
    struct Node{

        int EmployeeID;
        float Salary;
        struct Node* left;
        struct Node* right;
    };

    struct Node* insert(struct Node* root,int ID, float Salary){



        printf("Enter Employee ID: ");
        scanf("%d", &ID);

        printf("Enter Employee Salary: ");
        scanf("%f", &Salary);

        if(root == NULL){

            root = (struct Node*)malloc(sizeof(struct Node));
            root->EmployeeID = ID;
            root->Salary = Salary;
            root->left=root->right= NULL;
        }

        else if(ID < root->EmployeeID)
            root->left = insert(root->left, ID, Salary);
        else
            root->right = insert(root->right, ID, Salary);

    return root;

    };

    void PrePrint(struct Node* root){

        if(root == NULL)
            return;

        printf("%d   %.2f", root->EmployeeID, root->Salary);
        PrePrint(root->left);
        PrePrint(root->right);

        return;
    }
    int main()
    {
        int N, i;
        struct Node* root;
        int ID;
        int Sal;
        root = NULL;

        printf("How many Employee you would like to enter? \n");
        scanf("%d", &N);

        for(i=0; i<N; i++){

            root = insert(root, ID, Sal);
            printf("\n");

        }
            PrePrint(root);
        }
c data-structures binary-search-tree
2个回答
1
投票

删除插入函数中的第一个语句root = NULL;


1
投票

为了将scanf保留在insert函数中,您需要做一个标记来知道这是您第一次初始化变量(id和薪水),还是已经有值并且不想再次scanf。

#include <stdio.h>
#include <stdlib.h>
struct Node{

    int EmployeeID;
    float Salary;
    struct Node* left;
    struct Node* right;
};

struct Node* insert(struct Node* root,int ID, float Salary){
    if(ID==-1 && Salary==-1)
    {
        printf("Enter Employee ID: ");
        scanf("%d", &ID);

        printf("Enter Employee Salary: ");
        scanf("%f", &Salary);

    }
    if(root == NULL){

        root = (struct Node*)malloc(sizeof(struct Node));
        root->EmployeeID = ID;
        root->Salary = Salary;
        root->left=NULL;
        root->right= NULL;
    }

    else if(ID < root->EmployeeID)
        root->left = insert(root->left, ID, Salary);
    else
        root->right = insert(root->right, ID, Salary);

return root;

};

void PrePrint(struct Node* root){

    if(root == NULL)
        return;

    printf("%d   %.2f\n", root->EmployeeID, root->Salary);
    PrePrint(root->left);
    PrePrint(root->right);

return;
}
int main()
{
    int N, i;
    struct Node* root;
    int ID;
    float Salary;
    root = NULL;

    printf("How many Employee you would like to enter? \n");
    scanf("%d", &N);

    for(i=0; i<N; i++){
        root = insert(root, ID=-1, Salary=-1);
        printf("\n");

    }
        PrePrint(root);
    }
© www.soinside.com 2019 - 2024. All rights reserved.