2
我想爲我的二叉樹創建一個複製構造函數。二叉樹 - 複製構造函數
我的問題:
我可以看到源代碼樹的價值越來越被複制到目標樹,但是當它涉及到的值寫出來,也有複製的樹沒有價值,它崩潰的我程序。
錯誤消息:binTree.exe在0x0097a43c
未處理的異常:0000005:訪問衝突讀取位置0xccccccec。
代碼:
//主要方法
int main(int argc, char **) {
ifstream fin6("input_data.txt");
ofstream out9("copied_tree.txt");
if(!fin6.is_open())
{
cout << "FAIL" << endl;
return 1;
}
BinaryTreeStorage binaryTreeStorage2;
// read in values into data structure
binaryTreeStorage2.read(fin6);
BinaryTreeStorage binaryTreeStorage3 = binaryTreeStorage2;
// output values in data structure to a file
binaryTreeStorage3.write(out9);
fin6.close();
out9.close();
// pause
cout << endl << "Finished" << endl;
int keypress; cin >> keypress;
return 0;
}
//拷貝構造函數
BinaryTreeStorage::BinaryTreeStorage(BinaryTreeStorage &source)
{
if(source.root == NULL)
root = NULL;
else
copyTree(this->root, source.root);
}
//複製樹方法
void BinaryTreeStorage::copyTree(node *thisRoot, node *sourceRoot)
{
if(sourceRoot == NULL)
{
thisRoot = NULL;
}
else
{
thisRoot = new node;
thisRoot->nodeValue = sourceRoot->nodeValue;
copyTree(thisRoot->left, sourceRoot->left);
copyTree(thisRoot->right, sourceRoot->right);
}
}
我最初交換了引用部分和指針部分。它現在應該工作。 –
完美的作品,非常感謝。 – MitchellT
謝謝你的鏈接,這很好解釋。 – MitchellT