我正在为二叉搜索树编写构造函数,问题是树中的帮助函数被无限调用,最终会产生堆栈溢出。二进制搜索树的复制构造函数被无限调用
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.S数据对象不是原始数据类型,但它没有动态内存分配。
是'myTreeNode :: left'总是被初始化为'NULL'?如果不是,你可能永远不会达到基本情况,因为getLeft()永远不会返回NULL。不过,我认为垃圾价值会导致分段错误。 – 2011-04-17 21:28:21