首页 > 解决方案 > C - 二叉树的实现导致插入时出现奇怪的行为

问题描述

我有这样的二叉树设置:

`

我还像这样初始化 BT 的第一个节点:

`

到目前为止一切正常。但是,当我尝试插入我的 BT 时,我不断收到意外行为。我的插入函数看起来像这样。

`

但是,当我从 main 函数运行代码并尝试插入 BT 时,第一个节点显示得很好,但第二个节点变成了一个大而奇怪的数字。当我在调试器中运行它时,它会显示我期望的数字,但这不是打印出来的数字。这是我的主要方法。

`

问题出在我的插入函数中,但我不确定出了什么问题,因为当我通过调试器运行它时,我得到了预期值 5 和 6。

标签: crecursionbinary-search-treedynamic-memory-allocationfunction-definition

解决方案


在这些陈述中

struct Node* node1 = (struct Node*) malloc(sizeof(struct Node*));
                                                  ^^^^^^^^^^^^
struct Node* node2 = (struct Node*) malloc(sizeof(struct Node*));
                                                  ^^^^^^^^^^^^ 

您错误地分配了内存。而是写

struct Node* node1 = (struct Node*) malloc(sizeof(struct Node));
                                                  ^^^^^^^^^^^ 
struct Node* node2 = (struct Node*) malloc(sizeof(struct Node));
                                                  ^^^^^^^^^^^^  

函数中也存在同样的问题insert

同样在函数内将return语句移动到函数的末尾

struct Node* insert(struct Node* rootPtr, struct Node* node) {
    if (rootPtr == NULL) {
        rootPtr = (struct Node*) malloc(sizeof(struct Node));
        rootPtr->data = node->data;
        rootPtr->left = NULL;
        rootPtr->right = NULL;
    }

    if (rootPtr->data > node->data) {
        rootPtr->left = insert(rootPtr->left, node);
    } else if (rootPtr->data < node->data) {
        rootPtr->right = insert(rootPtr->right, node);
    }

    return rootPtr;
}

请注意,将指向整个节点的指针作为第二个参数传递是低效且容易出错的。你可以只传递一个整数。所以函数应该声明为

struct Node* insert(struct Node* rootPtr, int data );

推荐阅读