【发布时间】:2015-09-03 08:58:40
【问题描述】:
我是 C/C++ 编程的新手。我正在尝试编写二叉树代码并找到它的 PreOrder、PostOrder、InOrder 结构。到目前为止,我在 3 级子树上做得很好,但是当我尝试添加更多子树(4 级)时,我收到“进程返回 -1073741819(0xC0000005)”错误。我知道这是内存分配违规,我做了一些研究,但严重的是我不知道如何解决它。这是我的代码
#include <iostream>
#include <iostream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
struct node
{
string data;
struct node* left;
struct node* right;
};
/* allocates a new node with the NULL left and right pointers. */
struct node* newNode(string data)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
/* Given the tree, print nodes, postorder traversal. */
void printPostorder(struct node* node)
{
if (node == NULL)
return;
// first recur on left subtree
printPostorder(node->left);
// then recur on right subtree
printPostorder(node->right);
// now deal with the node
// printf("%d ", node->data);
cout << node->data;
}
/* print nodes in inorder*/
void printInorder(struct node* node)
{
if (node == NULL)
return;
/* first recur on left child */
printInorder(node->left);
/* then print the data of node */
// printf("%d ", node->data);
cout << node->data;
/* now recur on right child */
printInorder(node->right);
}
/* print nodes in preorder*/
void printPreorder(struct node* node)
{
if (node == NULL)
return;
/* first print data of node */
// printf("%d ", node->data);
cout << node->data;
/* then recur on left sutree */
printPreorder(node->left);
/* now recur on right subtree */
printPreorder(node->right);
}
int main()
{
struct node *root = newNode("A");
root->left = newNode("B");
root->right = newNode("C");
root->left->left = newNode("D");
root->left->right = newNode("E");
root->right->left = newNode("F");
root->right->right = newNode("G");
root->left->right->left = newNode("H");
root->left->right->right = newNode("I");
root->right->left->left = newNode("J"); // if i delete this, all is fine
root->right->left->right = newNode("K"); // if i delete this, all is fine
printf("\n Preorder traversal of binary tree is \n");
printPreorder(root);
printf("\n Inorder traversal of binary tree is \n");
printInorder(root);
printf("\n Postorder traversal of binary tree is \n");
printPostorder(root);
return 0;
}
对不起,我的英语不好,希望大家理解。并提前感谢:)
【问题讨论】:
-
你应该
free所有为初学者分配的内存。 -
那是一个崩溃。您应该在调试器中运行以捕获它,并且调试器将在崩溃的位置停止,让您检查调用堆栈(如果需要,也可以向上走)以及变量的值。