[英]Turn an array of structs into a binary search tree
所以我有一个结构数组,我想把它变成一个二叉搜索树。这就是我的代码的样子。
typedef struct Student{
char name[25];
char surname[25];
char Id[8];
double grade;
}Student;
struct TNode
{
struct TNode* data;
struct TNode* left;
struct TNode* right;
};
struct TNode* newNode(struct TNode* data);
/* A function that constructs Balanced Binary Search Tree from a sorted array
*/
struct TNode* sortedArrayToBST(struct Student** students, int start, int end)
{
/* Base Case */
if (start > end)
return NULL;
/* Get the middle element and make it root */
int mid = (start + end)/2;
struct TNode *root = newNode(students[mid]);
/* Recursively construct the left subtree and make it
left child of root */
root->left = sortedArrayToBST(students, start, mid-1);
/* Recursively construct the right subtree and make it
right child of root */
root->right = sortedArrayToBST(students, mid+1, end);
return root;
}
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct TNode* newNode(struct TNode * data)
{
struct TNode* node = (struct TNode*)
malloc(sizeof(struct TNode));
node->data = data;
node->left = NULL;
node->right = NULL;
return node;
}
/* A utility function to print preorder traversal of BST */
void preOrder(struct TNode* node)
{
if (node == NULL)
return;
printf("%s %s %s %.2f ", node->data);
preOrder(node->left);
preOrder(node->right);
}
这就是我如何调用我的主要功能。
struct TNode *root = sortedArrayToBST(&students, 0, n-1);
虽然结构数组在我的main函数中正常工作,但由于某些原因,这似乎不起作用。 在调用sortedArraytoBST函数之前,我总是在main中对结构数组进行排序。 请帮我。
我不能确定这个答案是否完整,因为你的代码不完整,所以我无法测试它。
仍然有一个“明显”的错误:你宣布
struct TNode* newNode(struct TNode* data);
但你打电话给它
struct TNode *root = newNode(students[mid]);
students[mid]
是struct Student *
。
不同类型的指针在C中不兼容。我想你想要的是一些“ 通用 ”B树。 在C中有一个解决方案: 通用指针是void *
。 您不能取消引用它,但您可以隐式地将其转换为任何其他(数据)指针类型。
所以你应该做的最少的是改变你的struct
:
struct TNode
{
void *data;
struct TNode *left;
struct TNode *right;
};
和你的功能原型:
struct TNode* newNode(void *data);
在你的preOrder
函数中,你尝试printf()
一个完整的结构 - >这是不可能的, printf()
每个转换说明符只需要一个参数! 所以改成它就好了(如果你知道data
总是指向一个struct Student
):
void preOrder(struct TNode* node)
{
if (node == NULL)
return;
struct Student *stud = node->data;
printf("%s %s %s %.2f ", stud->name, stud->surname, stud->id, stud->grade);
preOrder(node->left);
preOrder(node->right);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.