gpt4 book ai didi

c++ - 节点中的二叉搜索树数据始终为零

转载 作者:行者123 更新时间:2023-11-28 07:15:35 25 4
gpt4 key购买 nike

我已经在我的二进制搜索树上工作了一段时间,这些函数似乎可以工作,但我遇到了与我在进行链表程序分配时遇到的相同问题。我的节点似乎不想存储数据。我不知道是什么问题。当我打印时,它只打印零,正确数量的零,但仍然只是零。这是我的节点代码。我应该提到这是 C++。

class Node{
friend class BST;
private:
int data;
Node *left;
Node *right;
public:
Node(int data);
};

我的添加函数是:

void BST::add(Node* node, int d) {
if (root == NULL) {
root = new Node(d);
}
else if (d <= node->data) {
if (node->left == NULL) {
node->left = new Node(d);
}
else {
add(node->left, d);
}
}
else if (d > node->data) {
if (node->right == NULL) {
node->right = new Node(d);
}
else {
add(node->right, d);
}
}
}

为什么它不存储数据?

最佳答案

请将您的 Node::Node(int) 修改为:

Node::Node(int data) {
left = NULL;
right = NULL;
this->data = data;
}

您的评论中描述的Node::Node() 根本不存储数据;并且您的 BST::add() 依赖它将值存储到 Node 中。

关于c++ - 节点中的二叉搜索树数据始终为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20277716/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com