对于我的学校作业,我必须实现AVL树节点插入。我有这个单元测试,有4个测试,其中2个总是失败。 我使用了两个全局变量,一个是用于存储数字的数组,另一个是用于索引的整数。
int pom = 0;
int test_output[1000];
前2个测试与父母一起检查轮换:
void test_right_rotation_with_parent() {
//Arrange
struct Node* root = NULL;
int insert_nodes[] = { 15,10,5 };
int correct_output[] = { 10,2,5,1,15,1 }; // node -> key, node -> height;
char* passed = PASSED;
//Act
for (int i = 0; i < 3; i++) {
insert(root, insert_nodes[i]);
}
preOrder(root);
//Assert
for (int i = 0; i < 6; i++) {
if (correct_output[i] != test_output[i]) {
passed = FAILED;
break;
}
}
printf("%s: %s\n", __func__, passed);
}
输出:test_right_rotation_with_parent:通过。
对左旋转进行相同的测试。然后我有2个没有父母的轮换测试。这些是我无法通过的测试。
void test_right_rotation_without_parent() {
//Arrange
struct Node* root = NULL;
int insert_nodes[] = { 20,25,15,10,5 };
int correct_output[] = { 20,3,10,2,5,1,15,1,25,1 }; // node -> key, node -> height;
char* passed = PASSED;
//Act
for (int i = 0; i < 5; i++) {
insert(root, insert_nodes[i]);
}
preOrder(root);
...
}
输出:test_right_rotation_without_parent:失败
预购:
void preOrder(struct Node *root) {
if (root != NULL) { // this is the main problem if a node hasn't got parent
test_output[pom++] = root->key;
test_output[pom++] = root->height;
preOrder(root->link[0]); // left side
preOrder(root->link[1]); // right side
}
}
这是插入功能的一部分,它创建一个Node,如果以前没有的话。
struct Node *insert(struct Node *node, int key)
{
if (node == NULL)
{
struct Node *node = malloc(sizeof *node);
if (node != NULL)
{
/* if I do the same thing here which I did in preOrder,
* the sequence of the keys will be correct,
* however the height will always be 1 (for the without parent functions) */
node->key = key;
node->height = 1;
node->link[0] = node->link[1] = NULL;
}
return node;
}
else {...}
是否可以使用此方法进行这项工作?或者如果我想通过这些测试,我需要找到另一种方法?