二叉搜索树的复制构造函数被无限调用
Copy constructor for a binary search tree is being called infinitely
我正在写一个二叉搜索树的构造函数,问题是树中的辅助函数被无限调用,这最终会产生堆栈溢出。
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 !)
相关文章:
- 什么时候调用组成单元对象的析构函数
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 函数调用中参数的顺序重要吗
- OpenGL - 在抛出"__gnu_cxx::recursive_init_error"实例后终止调用?
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 在c++类上调用void函数
- 为什么 std::unique 不调用 std::sort?
- 调用专用模板时出错"no matching function for call to [...]"
- 实现递归函数,避免由 C++ 中 include 的循环调用(没有 #pragma 一次)引起的无限循环输入
- 如果无限循环在C 中仍然不确定的行为,如果它调用共享库
- 尽管有停止条件,无限递归调用仍会执行,因为参数不会前进
- 为什么“fork()”调用没有在无限循环中优化掉
- 调用原始版本的DLL挂钩函数时,我得到了无限递归
- 在无限 while 循环中调用 Sleep() 有多重要
- 从模板类调用函数时形成的无限循环,请任何人解释
- C++ 子类和运算符=:无限循环和意外调用
- 类成员函数正常工作,但当作为另一个类的数据成员调用时陷入无限循环
- 二叉搜索树的复制构造函数被无限调用