【发布时间】:2017-06-10 15:21:37
【问题描述】:
所以我有一个结构数组,我想将其变成二叉搜索树。这是我的代码的样子。
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);
}
这是我在 main 中调用函数的方式。
struct TNode *root = sortedArrayToBST(&students, 0, n-1);
尽管结构数组在我的 main 函数中可以正常工作,但由于某种原因,这似乎不起作用。在调用 sortedArraytoBST 函数之前,我总是在 main 中对结构数组进行排序。请帮帮我。
【问题讨论】:
-
你的编译器没有在
struct TNode *root = newNode(students[mid]);上给你一些警告吗? -
是的,但我不明白为什么。
标签: c arrays struct binary-search-tree