2011-04-17 53 views
1

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

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數據對象不是原始數據類型,但它沒有動態內存分配。

+1

是'myTreeNode :: left'總是被初始化爲'NULL'?如果不是,你可能永遠不會達到基本情況,因爲getLeft()永遠不會返回NULL。不過,我認爲垃圾價值會導致分段錯誤。 – 2011-04-17 21:28:21

回答

4

我不知道這可能是如何造成無限遞歸,但你的getLeft()功能似乎是可疑的。您正在返回對堆棧中某個東西的引用。誰知道那之後發生了什麼。它看起來像你一直在內存中反覆使用同一個插槽,所以你可能會創建一個循環而不是樹。

更改它,使其返回一個指針,而不是對指針的引用(刪除'&')。

+0

好的調用 - 我認爲你對內存行爲的感覺與我期望任何C編譯器在正常情況下所做的一致。 – leoger 2011-04-18 00:10:59

+0

你是對的這是通過引用的返回,使我在 – sola 2011-04-18 23:57:21

1

@JCooper想通了 - 我只是提供示例代碼。 getLeft()函數應該看起來更像這樣。請注意,我沒有創建任何NEW變量,所以沒有堆棧壽命問題。

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

(編輯:做代碼更簡潔感謝@molbdnilo!)

+1

你可以更簡潔地表達:如果'this-> left'非空,則返回'this-> left';如果它爲null,則返回空指針,它是'this-> left'的值。所以你可以用'return this-> left'替換'getLeft'的整個主體。 – molbdnilo 2011-04-18 04:43:09

+0

謝謝,修正了這個問題 – sola 2011-04-18 23:56:22

+0

我的意圖最初是爲了明確兩個案例的目的應該是冗長的。現在,我認爲你說得對,這太浪費了,評論可能是更清晰的選擇! – leoger 2011-04-19 05:23:05