【问题标题】:C - Implementation of Binary Tree Causing Strange Behavior on InsertC - 二叉树的实现导致插入时出现奇怪的行为
【发布时间】:2021-12-02 09:01:07
【问题描述】:

我的二叉树设置如下:

`

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

`

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

`

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

`

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

【问题讨论】:

  • 插入后缺少返回
  • malloc(sizeof(struct Node*)) 应该是malloc(sizeof(struct Node))
  • 为什么initializeTree() 采用Node 参数而不仅仅是数据?
  • 如果insert() 会在您使用NULL 根插入时创建根节点,那您为什么还需要initializeTree()
  • @Barmar 是的,我刚刚意识到这一点。你完全正确!

标签: c recursion binary-search-tree dynamic-memory-allocation function-definition


【解决方案1】:

在这些陈述中

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 );

【讨论】:

  • 关于那个说明,在返回函数的那个​​ if 语句中,我认为我的 malloc 也有错误。让我试试这个。一会儿会接受答案。事实上,我在我调用它的任何地方都 malloc 错误。非常感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多