【发布时间】:2020-05-27 10:30:19
【问题描述】:
我试图插入 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