二叉搜索树的复制构造函数被无限调用

Copy constructor for a binary search tree is being called infinitely

本文关键字:无限 调用 构造函数 复制 搜索树      更新时间:2023-10-16

我正在写一个二叉搜索树的构造函数,问题是树中的辅助函数被无限调用,这最终会产生堆栈溢出。

void copyTree(myTreeNode* & copy, const myTreeNode* & originalTree)
{
    if(originalTree==NULL)
    {
        copy=NULL;
    }
    else
    {
        copy=new myTreeNode();
        cout<<"This is the data my friend: "<<endl<<copy->data.getCharacter()<<endl;
        copy->data=originalTree->data;
        copyTree(copy->left, originalTree->getLeft());
        copyTree(copy->right,originalTree->getRight());
    }
}
//this is the copy constructor for the tree
myTree (const myTree & copy)
{
    this->copyTree(this->root,copy.getRoot());
}
//and this is the way I have written the getLeft and getRight Functions
//they both return references to the left and rightNodes
const myTreeNode *& getLeft() const
{
    const myTreeNode*  ptr=NULL;
    if(this->left)
    {
        ptr=this->left;
    }
    return ptr;
}

p。数据对象不是原始数据类型,但它没有动态内存分配。

我不确定这可能会导致无限递归,但您的getLeft()函数似乎很可疑。你正在返回对堆栈上某个东西的引用。谁知道那之后的记忆会怎样。看起来好像你一直在一次又一次地使用同一个内存槽,所以你可能是在创建一个循环,而不是一个树。

修改它,使它返回一个指针,而不是一个指针的引用(去掉'&')。

@JCooper弄清楚了——我只是提供示例代码。getLeft()函数应该更像这样。请注意,我没有创建任何新变量,所以没有堆栈寿命问题。

const myTreeNode * getLeft() const
{
    //may be NULL
    return this->left;
}

(编辑:使代码更简洁。谢谢@molbdnilo !)