gpt4 book ai didi

c++ - 以当前节点为根的二进制搜索树插入 C++

转载 作者:行者123 更新时间:2023-11-28 03:45:37 25 4
gpt4 key购买 nike

我需要将一个项目添加到二叉树中,只给定要添加的项目。

这是我得到的代码:

void BinaryTree::add(Data * data) {
if (root == NULL) {
root = new BinaryTreeNode(data);
}
else {
root->add(data);
}
}

其中 root 是定义为 BinaryTreeNodeBinaryTree 的私有(private)变量。

我需要实现一个方法:

void BinaryTreeNode::add(Data * data);

BinaryTreeNode 是:

class BinaryTreeNode {
public:
Data * nodeData;
BinaryTreeNode * left;
BinaryTreeNode * right;

/**
* Constructor
*/
BinaryTreeNode(
Data * data,
BinaryTreeNode * left = NULL,
BinaryTreeNode *right = NULL
)
: nodeData(data), left(left), right(right)
{ }

// ...

我想递归地执行此操作,但我不确定当您只传递要添加的数据时如何。

我的想法是行不通的:

void BinaryTreeNode::add(Data * newData) {
BinaryTreeNode * temp = this;
if (temp == NULL) {
temp->nodeData = newData;
} else {
if (newData->compareTo(nodeData) < 0) {
temp->left->add(newData);
} else {
temp->right->add(newData);
}
}
}

最佳答案

您将 temp 设置为此,然后将其与 NULL 进行比较。这永远不应该为 NULL。需要检查左右是否为NULL。

关于c++ - 以当前节点为根的二进制搜索树插入 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7787713/

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