[英]binary search tree assignment operator
我在二叉搜索樹中的遞歸函數遇到了很大的問題。 我的項目要在幾個小時內到期,我一生都無法找到我的老師。
我的功能似乎只遍歷我樹的最左側分支。
分配運算符:
template<typename Type>
BST<Type>& BST<Type>::operator=(const BST& that)
{
if(this != &that)
{
this->clear();
Node *c = that.root;
preORet(c);
}
return *this;
}
遞歸函數調用:
template<typename Type>
void BST<Type>::preORet(Node *c)
{
this->insert(c->data);
if(c->left != nullptr)
preORet(c->left);
else if(c->right != nullptr)
preORet(c->right);
}
順便說一句,我理解很多這樣的代碼看起來都像是混蛋,但是這正是我的老師期望的樣子。
先感謝您。
您的問題就在這里:
if(c->left != nullptr)
preORet(c->left);
else if(c->right != nullptr)
preORet(c->right);
如果你不想else if
。 無論左側子樹是否為nullptr,都希望遍歷右側子樹。
正如其他人指出的那樣,除了在preORet()
函數中preORet()
else
之外,還值得注意的是,如果您碰巧通過參數Node *c
傳遞了一個空指針,則會遇到分段錯誤(錯誤代碼11)。 Node *c
。
這是一個解決方案:
template<typename Type>
void BST<Type>::preORet(Node *c)
{
if (c != nullptr)
{
this->insert(c->data);
preORet(c->left);
preORet(c->right);
}
}
這樣,在使用每個指針之前,都要檢查它是否為空,包括左指針和右指針。 如果為null,它將超出范圍。
擺脫preORet()中的else。
擺脫else
。
乍一看,您的設計看起來很容易move
或swap
,我將使用copy- swap
慣用法生成合理有效,易於編寫的operator=
。
但是,這只是我。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.