我在二叉搜索树中的递归函数遇到了很大的问题。我的项目要在几个小时内到期,我一生都无法找到我的老师。
我的功能似乎只遍历我树的最左侧分支。
分配运算符:
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,您都希望遍历右侧子树。