gpt4 book ai didi

c++ - 二叉搜索树赋值运算符

转载 作者:行者123 更新时间:2023-11-27 23:11:42 26 4
gpt4 key购买 nike

我的二叉搜索树中的递归函数有一个大问题。我的项目将在几个小时后到期,但我这辈子都联系不上我的导师。

我的函数似乎只遍历树的最左边的分支。

赋值运算符:

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,您都希望遍历右子树。

关于c++ - 二叉搜索树赋值运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19871550/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com