二叉搜索树插入 C++以当前节点为根
我需要将一个项目添加到二叉树中,仅给出要添加的项目。
这是我给出的代码:
void BinaryTree::add(Data * data) {
if (root == NULL) {
root = new BinaryTreeNode(data);
}
else {
root->add(data);
}
}
其中 root
是定义为 BinaryTreeNode
的 BinaryTree
的私有变量。
我需要实现一个方法:
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);
}
}
}
I need to add an item to a binary tree given only the item to be added.
Here is the code I'm given:
void BinaryTree::add(Data * data) {
if (root == NULL) {
root = new BinaryTreeNode(data);
}
else {
root->add(data);
}
}
where root
is a private variable of a BinaryTree
defined as a BinaryTreeNode
.
I need to implement a method:
void BinaryTreeNode::add(Data * data);
where a BinaryTreeNode
is:
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)
{ }
// ...
I want to do this recursively, but I'm not positive how when you're only passed the data to be added.
My idea that doesn't work is:
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);
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您将 temp 设置为此,然后将其与 NULL 进行比较。这不应该是 NULL。您需要检查左侧和右侧是否为 NULL。
You are setting temp to this and then comparing it to NULL. this should never be NULL. You need to check if the left and right are NULL.
好吧,一棵二叉树,至少我知道如何实现涉及如下两个对象,一个包含树节点对象,另一个充当整个树的接口。
当您比较输入数据的实际值并相应地放置它时,这相当于二叉搜索树。然后插入函数可以写为
递归查找函数将类似于
希望这会有所帮助。
Well a binary tree, atleast how I know how to implement involves something like the following with two objects, one containing the the treenode object, and the other acting as an interface for the whole tree.
As you are comparing the actually value of the input data and placing it accordingly, this qualifies as a binary search tree. Then the insertion function can be written as
The recursive lookup function will be something like
Hope this helps.