我很新的C/C++編程。我試圖編寫二叉樹代碼,並找到它的PreOrder,PostOrder,InOrder結構。到目前爲止,我做的3級子樹,但是當我嘗試添加更多的孩子(4級),我得到「進程返回-1073741819(0xC0000005)」錯誤。我知道這是內存分配違規,我做了一些研究,但認真,我不知道如何解決它。這裏是我的代碼樹二進制C/C + +過程返回-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;
}
對不起,我的英語不好,希望你們都明白。並提前感謝:)
你應該'釋放所有分配給初學者的內存。 – ameyCU
這是一個*崩潰*。您應該在調試器中運行以捕獲它,調試器將停在崩潰位置,讓您檢查調用堆棧(如果需要,也可以逐步調用)以及變量值。 –