即使使用 "new" 关键字,二进制搜索树插入也不会在堆上创建数据
Binary Search Tree insert not creating data on the heap even though the "new" keyword is used
我的代码有问题,因为它没有在堆上插入节点。我 GDBed 代码以查看发生了什么,我发现它正确地插入了数据并创建了一个节点,但是在函数结束后节点被销毁并将其重置为 NULL。所以我认为它没有在堆上正确创建,但我使用 "new" 关键字所以我很困惑。无论如何,我的代码如有任何帮助,将不胜感激。
int BST::insert(int data)
{
int isSuccess;
if(head == NULL)
{
head = new BSTNode(data);
return data;
}
else
{
if(data < head->data)
isSuccess = insertTreeNode(head->left,data);
else if(data > head->data)
isSuccess = insertTreeNode(head->right,data);
else
return 0;
}
return isSuccess;
}
这是一个辅助功能
int BST::insertTreeNode(BSTNode* temp,int data)
{
int returnVal = data;
if(temp == NULL)
temp = new BSTNode(data);
else if(data < temp->data)
returnVal = insertTreeNode(temp->left,data);
else if(data > temp->data)
returnVal = insertTreeNode(temp->right,data);
else
returnVal = 0;
return returnVal;
}
这是 BSTNode 的 h 文件
#ifndef BSTNODE_H
#define BSTNODE_H
#include <iostream>
using namespace std;
class BSTNode
{
public:
BSTNode* left;
BSTNode* right;
int data;
BSTNode(int);
private:
};
#endif
抱歉格式问题。 head 也是一种类型 BSTNode*
发生的事情是您正在函数内部更改指针,但在函数外部看不到它。
将您的函数签名更改为:
int BST::insertTreeNode(BSTNode * & temp,int data)
我不会对您代码的任何其他部分发表评论。
我的代码有问题,因为它没有在堆上插入节点。我 GDBed 代码以查看发生了什么,我发现它正确地插入了数据并创建了一个节点,但是在函数结束后节点被销毁并将其重置为 NULL。所以我认为它没有在堆上正确创建,但我使用 "new" 关键字所以我很困惑。无论如何,我的代码如有任何帮助,将不胜感激。
int BST::insert(int data)
{
int isSuccess;
if(head == NULL)
{
head = new BSTNode(data);
return data;
}
else
{
if(data < head->data)
isSuccess = insertTreeNode(head->left,data);
else if(data > head->data)
isSuccess = insertTreeNode(head->right,data);
else
return 0;
}
return isSuccess;
}
这是一个辅助功能
int BST::insertTreeNode(BSTNode* temp,int data)
{
int returnVal = data;
if(temp == NULL)
temp = new BSTNode(data);
else if(data < temp->data)
returnVal = insertTreeNode(temp->left,data);
else if(data > temp->data)
returnVal = insertTreeNode(temp->right,data);
else
returnVal = 0;
return returnVal;
}
这是 BSTNode 的 h 文件
#ifndef BSTNODE_H
#define BSTNODE_H
#include <iostream>
using namespace std;
class BSTNode
{
public:
BSTNode* left;
BSTNode* right;
int data;
BSTNode(int);
private:
};
#endif
抱歉格式问题。 head 也是一种类型 BSTNode*
发生的事情是您正在函数内部更改指针,但在函数外部看不到它。
将您的函数签名更改为:
int BST::insertTreeNode(BSTNode * & temp,int data)
我不会对您代码的任何其他部分发表评论。