我正在尝试编写各种方法来创建二叉树,其中之一是从现有的二叉树中复制方法
从向量创建树
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);
}
} Main
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:未解析的外部符号"public: void __thiscall binary_tree::copyTree(struct node * &,struct node * &)“(?copyTree@binary_tree@@QAEXAAPAUnode@@0@Z)在"public:__thiscall binary_tree::binary_tree(class binary_tree const &)”(??0binary_tree@@QAE@ABV0@@Z)中引用
发布于 2016-04-13 13:02:20
它在您发布的代码中是不可见的,但我相当肯定您的标题包含如下内容:
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) {...}或者通过从头中删除它(如果选择此路径,请确保copyTree在其使用(binary_tree(const binary_tree &rhs) )之前在源中定义(或至少声明))。
https://stackoverflow.com/questions/36581608
复制相似问题