我正在爲二叉搜索樹編寫構造函數,問題是樹中的幫助函數被無限調用,最終會產生堆棧溢出。二進制搜索樹的複製構造函數被無限調用
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