[英]How can I read the data from the user and use them in the same function that I'll insert nodes in the BST
我有一个 C 编程课程评估。 他们要求创建一个 function 来为 BST 插入新节点。 在同一个 function 中,我必须填写来自用户的 N 个数据(ID 和 Salary)。 并且主要我会要求用户输入他/她想要输入多少数据并调用插入 function。
我做了以下事情,这是 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;
}
您必须在 BST 中循环并插入任何新节点作为离开。 标准插入 function 到 BST 将如下 -
假设您将树根声明为binary_search_tree *t = new_binary_search_tree();
您可以将输入读取为-
int EmployeeID;
scanf("%d",&EmployeeID);
float salary;
scanf("%d",&salary);
然后你可以创建一个新节点 -
node* n = new_node(EmployeeID,salary);
并将其传递给下面的插入 function。
void insert(binary_search_tree *t, node *n) {
node *y = NULL;
node *temp = t->root;
while(temp != NULL) {
y = temp;
if(n->data < temp->data)
temp = temp->left;
else
temp = temp->right;
}
n->parent = y;
if(y == NULL) //newly added node is root
t->root = n;
else if(n->data < y->data)
y->left = n;
else
y->right = n;
}
new_node function 将是 -
node* new_node(int emp_id,float sal) {
node *n = malloc(sizeof(node));
n->EmployeeID= emp_id;
n->salary= sal;
n->left = NULL;
n->right = NULL;
n->parent = NULL;
return n;
}
这会将新节点作为叶节点插入到您的 BST。 您可以将此片段作为参考并进行相应修改。
根据请求,我被要求在插入 function 本身中输入。 所以这里 -
void insert(binary_search_tree *t, int N) {//N is number of nodes to be added
for(int i=0;i<N;i++){
int EmployeeID;
scanf("%d",&EmployeeID);
float salary;
scanf("%d",&salary);
node* n = new_node(EmployeeID,salary);
node *y = NULL;
node *temp = t->root;
while(temp != NULL) {
y = temp;
if(n->data < temp->data)
temp = temp->left;
else
temp = temp->right;
}
n->parent = y;
if(y == NULL) //newly added node is root
t->root = n;
else if(n->data < y->data)
y->left = n;
else
y->right = n;
}
}
这是我用来保留根节点的 binary_serach_tree 结构 -
typedef struct binary_search_tree {
node *root;
}binary_search_tree;
节点结构与您的相同。 但是,如果您没有在结构节点定义中使用typedef
,请记住使用关键字struct Node*
而不是我在代码中使用的Node *
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.