Tree Binary C/C++进程返回-1073741819(0xC0000005)

0 c++ segmentation-fault

我是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;
}
Run Code Online (Sandbox Code Playgroud)

抱歉我的英文不好,希望大家都明白.并提前感谢:)

Som*_*ude 6

一个主要问题和未定义行为的来源(可能导致您的崩溃)是您正在使用malloc分配您的结构.问题在于它实际上并没有构造你的对象,它只是分配内存.这意味着节点中的字符串成员将无法正确构造,并导致所述未定义的行为.

在C++中分配任何类型的内存时,您应该使用new:

node* node = new struct node;
Run Code Online (Sandbox Code Playgroud)

注意:您必须在struct此处使用关键字,因为您的类型和变量具有相同的名称.