PC2中存在运行时错误,但在Dev-C++中有效



我正在试着做作业。对于示例输入和输出,我的代码是成功的,但当涉及到PC2测试时,它有运行时错误,我不知道为什么。我必须给一个有序遍历二叉树给定的前序和后序。这是我的代码:

#include <stdio.h>
#include <stdlib.h>
typedef struct Node Node;
struct Node { 
int data; 
Node *left; 
Node *right; 
}; 
Node *getNewNode(int data) { 
Node *newNode = (Node*)malloc(sizeof(Node)); 
newNode->data = data; 
newNode->right = newNode->left = NULL; 
return newNode; 
}
Node *buildTreeRecur (int pre[], int post[], int* preIndex, int low, int high, int size) {
if (*preIndex >= size || low > high)
return NULL;
Node *root = getNewNode(pre[*preIndex]);
*preIndex++;
if (low == high)
return root;
int i;
for (i=low; i<=high; i++) {
if (pre[*preIndex] == post[i])
break;
}
if (i<=high) {
root->left = buildTreeRecur(pre, post, preIndex, low, i, size);
root->right = buildTreeRecur(pre, post, preIndex, i+1, high, size);
}
return root;
}
Node *buildTree (int pre[], int post[], int size) {
int preIndex = 0;
return buildTreeRecur(pre, post, &preIndex, 0, size-1, size);
}
void printInorder (Node *node) {
if (node == NULL)
return;
printInorder(node->left);
printf("%d ", node->data);
printInorder(node->right);
}
int main(int argc, char *argv[]) {
int numCase, size, i;
printf("Enter number of case: ");
scanf("%d", &numCase);
printf("Enter the size of tree: ");
scanf("%d", &size);
int pre[size], post[size];
printf("Enter the preorder tree:n");
for(i=0; i<size; i++) {
scanf("%d", &pre[i]);
}
printf("Enter the postorder tree:n");
for(i=0; i<size; i++) {
scanf("%d", &post[i]);
}
Node *root = buildTree(pre, post, size);
printf("The inorder traversal of the full binary tree: n");
printInorder(root);
return 0;
}

成功的输入案例如下。

1
9
1 2 4 8 9 5 3 6 7
8 9 4 5 2 6 7 3 1

输出为:

8 4 9 2 5 1 6 3 7

但我不知道我错过了什么导致运行时错误的案例。。

我知道Dev-C++中有一个调试器,我现在正在使用,但我也不知道如何使用它。

此处:

*preIndex++;

你推进指针。(然后你取消引用它并丢弃值。当你激活警告时,编译器应该告诉你未使用的值。不幸的是,在许多编译器中,警告默认是关闭的。打开它们。(

当指针指向数组时,推进指针是有用的,但preIndex指向单个int。推进指针后,它指向未定义的地方。这导致了未定义的行为,这意味着程序可能会崩溃或不崩溃。从现在起所有赌注都取消了。

您想要增加preIndex指向的整数索引:

(*preIndex)++;

相关内容

最新更新