我试图编写各种方法来创建二叉树,其中一个是现有二叉树的复制方法
从矢量
创建树binary_tree::binary_tree(const std::vector<int> &values)
{
for(int i = 0; i < 5; i++)
{
insert(values[i]);
}
}
插入节点
void insertnode(node **tree, int value)
{
if (*tree == nullptr)
{
*tree = new node;
(*tree)->data = value;
(*tree)->left = nullptr;
(*tree)->right = nullptr;
}
else
if(value < (*tree)->data)
{
insertnode(&(*tree)->left, value);
}
else if(value > (*tree)->data)
{
insertnode(&(*tree)->right, value);
}
else
return;
}
void binary_tree::insert(int value)
{
insertnode(&tree, value);
}
复制方法
binary_tree::binary_tree(const binary_tree &rhs)
{
copyTree(tree2, tree);
}
void copyTree(node *& tree2, node *& tree)
{
if(tree == NULL)
{
tree2 = NULL;
}
else
{
tree2 = new node;
tree2->data = tree->data;
copyTree(tree2->left, tree->left);
//cout << tree2->data << " ";
copyTree(tree2->right, tree->right);
}
}
印刷方法
std::string binary_tree::inorder() const
{
inorderof(tree);
std::string back2 = back.substr(0, back.length()-1);
back = "";
return std::string(back2);
void inorderof(node *tree)
{
if(tree != nullptr)
{
inorderof(tree->left);
back += to_string(tree->data);
back += " ";
inorderof(tree->right);
}
}
主要
int main(int argc, char **argv)
{
tree = new binary_tree(vector<int>{10, 5, 12, 15, 8});
tree->inorder();
binary_tree *tree2 = new binary_tree(*tree);
tree2->inorder();
}
我的问题是我必须复制初始树 - 构建和打印完美 - 并使用
复制它 binary_tree::binary_tree(const binary_tree &rhs)
方法,但是当树被复制时,我得到一些未解决的外部错误。
我试图在没有使用上述方法的情况下复制树,但是必须将初始二叉树作为参数传递给这个方法让我感到难过并且我不知道从那里去哪里。我必须使用这个确切的方法声明作为任务的一部分,否则我不会这样做!
错误消息:
错误LNK2019:未解析的外部符号&#34; public:void __thiscall binary_tree :: copyTree(struct node *&amp;,struct node *&amp;)&#34; (?copyTree @ binary_tree @@ QAEXAAPAUnode @@ 0 @ Z)在函数中引用 &#34; public:__ thiscall binary_tree :: binary_tree(class binary_tree const &安培;)&#34; (?? 0binary_tree @@ @ QAE @@ ABV0 Z)
答案 0 :(得分:0)
在您发布的代码中看不到它,但我相当确定您的标题包含以下内容:
class binary_tree {
...
void copyTree(node *& tree2, node *& tree);
...
}
并在您的源文件中:
void copyTree(node *& tree2, node *& tree)
{
if(tree == NULL)
{
tree2 = NULL;
}
else
{
tree2 = new node;
tree2->data = tree->data;
copyTree(tree2->left, tree->left);
//cout << tree2->data << " ";
copyTree(tree2->right, tree->right);
}
}
您可以通过将源文件中的签名更改为:
来解决此问题void binary_tree::copyTree(node *& tree2, node *& tree) {...}
或从标题中删除它(如果选择此路径,请确保在使用{(1}})之前在源中定义(或至少声明)copyTree
。