0

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

这是我给出的代码:

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

其中root是 a 的私有变量,BinaryTree定义为 a BinaryTreeNode

我需要实现一个方法:

void BinaryTreeNode::add(Data * data);

其中 aBinaryTreeNode是:

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);
        }
    }
}
4

2 回答 2

2

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

于 2011-10-16T22:21:32.813 回答
0

好吧,一棵二叉树,至少我知道如何实现涉及以下两个对象,一个包含 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.

希望这可以帮助。

于 2011-10-17T00:24:18.173 回答