我正在努力进行AVL树测试。我的程序按预期工作,但是我无法弄清楚如何将数字放入正确的形式。我的测试代码:
void test_left_rotation_with_parent() {
//Arrange
struct Node* root = NULL;
int insert_nodes[] = { 5,10,15 };
int test_output[6]; // this is where my numbers should be
int correct_output[] = { 10,2,5,1,15,1, };
char* passed = PASSED;
//Act
for (int i = 0; i < 3; i++) {
root = add(root, insert_nodes[i]);
}
preOrder(root); // this is my function, see below
int index = print_pre_order(root, test_output, 0); // I cannot figure out what this is for
//Assert
for (int i = 0; i < 6; i++) {
if (correct_output[i] != test_output[i]) {
passed = FAILED;
break;
}
}
printf("%s: %s\n", __func__, passed);
我有一个名为preOrder的函数,看起来像这样:
void preOrder(struct Node *root)
{
if (root != NULL)
{
printf("%d,", root->key);
printf("%d,", root->height);
preOrder(root->link[0]); // left
preOrder(root->link[1]); // right
}
}
输出:
10,2,5,1,15,1,test_left_rotation_with_parent: FAILED
我需要按此顺序将这些数字准确地放置到数组中,因此每个节点的键都放在第一位,高度到第二位。
您可以使用具有数组索引的全局变量。每次插入(您的printf
)都会增加变量。阵列也必须是全局的。 preOrder
现在看起来像:
int test_output[6], index=0; // is 6 large enough?
void preOrder(struct Node *root)
{
if (root != NULL)
{
test_output[index++]= root->key;
test_output[index++]= root->height;
preOrder(root->link[0]); // left
preOrder(root->link[1]); // right
}
}