【发布时间】:2020-09-13 03:58:13
【问题描述】:
我有一个 C 编程课程评估。 他们要求创建一个函数来为 BST 插入新节点。在同一个函数中,我必须填写来自用户的 N 个数据(ID 和 Salary)。并且主要我会要求用户输入他/她想要输入的数据并调用插入函数。
我做了以下事情,100% 错了:)
#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 N) {
int Key;
float Salary;
int i;
for (i = 0; i < N; i++) {
printF("Enter Employee ID: ");
scanf_s("%d", &Key);
printF("Enter Employee Salary: ");
scanf_s("%f", &Salary);
if (root = NULL) {
root = (struct Node*)malloc(sizeof(struct Node));
root->EmployeeID = Key;
root->Salary = Salary;
root->left = root->Right = NULL;
}
else if (Key < root->EmployeeID)
root->left = insert(root->left, Key);
else
root->Right = insert(root->Right, Key);
}
}
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 x;
struct Node* root = NULL;
struct Node*temp = (struct Node*)malloc(sizeof(struct Node));
temp = root;
printf("How many Employee would you like to enter? ");
scanf_s("%d", &x);
root= insert(root, x);
PrePrint(root);
return 0;
}
【问题讨论】:
-
请将问题中的代码作为文本发布。 IMO,您不应该将输入与插入功能混合在一起,但是您标记的那些行到底有什么不便?
-
当然,我会这样做的。这很不方便,因为这是我第一次这样做。
-
@it'sM 如果您觉得答案对您有所帮助,请勾选绿色勾号,将答案标记为已接受。
标签: c data-structures binary-search-tree insertion