所以我有一個結構數組,我想變成二叉搜索樹。這裏是我的代碼的樣子。將結構數組轉換爲二叉搜索樹
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);
由於某些原因,雖然結構數組在我的主函數內部工作正常,但這看起來沒有工作。在調用sortedArraytoBST函數之前,我總是在我的主內部對我的結構數組進行排序。請幫幫我。
沒有你的編譯器給你*'上結構TNODE *根= newNode(學生[MID])*一些警告;'? –
是的,但我不明白爲什麼。 –