我需要添加一个项目到一个二叉树只给予要添加的项目。二叉搜索树插入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);
}
}
}
没有很好的理由来编辑你的问题以外的代码。 – ildjarn