C++ 二叉搜索树插入C++;根在当前节点

C++ 二叉搜索树插入C++;根在当前节点,c++,recursion,binary-tree,insertion,C++,Recursion,Binary Tree,Insertion,我需要添加一个项目到一个二叉树中,只给出要添加的项目 下面是给我的代码: void BinaryTree::add(Data * data) { if (root == NULL) { root = new BinaryTreeNode(data); } else { root->add(data); } } 其中root是定义为BinaryTreeNode的BinaryTree的私有变量 我需要实现一种方法: void B

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

下面是给我的代码:

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);
        }
    }
}
void二进制树节点::添加(数据*newData){
二进制树节点*temp=此;
if(temp==NULL){
临时->节点数据=新数据;
}否则{
如果(新建数据->比较(节点数据)<0){
临时->左->添加(新数据);
}否则{
临时->右->添加(新数据);
}
}
}

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

好的,二叉树,至少我知道如何实现,包括以下两个对象,一个包含treenode对象,另一个作为整个树的接口

 class cBinaryTree {

 public:
 bool insert(int inData);
 //Other operations

 private:
 cBinaryTreeNode* root;
 bool leftInsertion;
 cBinaryTreeNode* getRoot() { return root; }
当您比较输入数据的实际值并相应地放置它时,这符合二叉搜索树的条件。然后,插入函数可以写成

bool cBinaryTree::insert(int inData) {

//handle case if its first node.
cBinaryTreeNode *Parent = getInsertionNodePosition(getRoot(), inData);
cBinaryTreeNode *newNode = createNewNode(inData);

if(leftInsertion) //insert into left. add return statement
    Parent->setLeftChild() = newNode;
else //insert into right 
}
递归查找函数类似于

cBinaryTreeNode* getInsertionNodePosition(cBinaryTreeNode* node,int inData) {

//Check left subtree and proceed from there.
if(inData < node->getData()) {
    if(node->getLeftChild() == NULL)  {             
        leftInsertion = true;
        return node;
    }
    else {
        node = node->getLeftChild();
        return getInsertionNodePosition(node, inData);
    }
}
    //Similarly Check right subtree.
cBinaryTreeNode*getInsertionNodePosition(cBinaryTreeNode*node,int-inData){
//检查左子树并从那里开始。
if(inDatagetData()){
如果(节点->getLeftChild()==NULL){
leftInsertion=true;
返回节点;
}
否则{
node=node->getLeftChild();
返回getInsertionNodePosition(节点,inData);
}
}
//类似地,检查右子树。

希望这能有所帮助。

谢谢,这正是我刚刚意识到的,我已经让它运行起来了。没有什么好的理由不考虑你的问题来编辑代码。