二叉搜索树 深度复制和取消引用
Binary Search Tree Deep copy and dereferencing
>我正在尝试为二叉搜索树设置一个深度复制构造函数,但似乎无法弄清楚如何处理指针的取消引用。我对C++很陌生,开始掌握它是如何工作的,但这打败了我。
代码如下:
void copyTree_helper(Node **destination,const Node *source)
{
{
if(source == NULL)
{
(*destination) = NULL;
}
else
{
(*destination) = new Node;
(*destination)->data = source->data;
copyTree_helper(&(*destination)->left, source->left);
copyTree_helper(&(*destination)->right, source->right);
}
}
}
// Creates a binary tree by copying an existing tree
BinarySearchTree::BinarySearchTree(const BinarySearchTree &rhs)
{
if(&rhs == nullptr)
root = nullptr;
else
copyTree_helper(&(*root), &rhs);
/*////////////////////////////////////////////
Needs implementation
////////////////////////////////////////////*/
}
.h 文件中二叉搜索树的实现如下所示。
struct Node
{
// Data stored in this node of the tree
std::string data;
// The left branch of the tree
Node *left = nullptr;
// The right branch of the tree
Node *right = nullptr;
};
现在它不会编译以下错误消息:
BinarySearchTree.cpp:44:9: error: no matching function for call to 'copyTree_helper'
copyTree_helper(&(*root), &rhs);
^~~~~~~~~~~~~~~
BinarySearchTree.cpp:20:6: note: candidate function not viable: no known conversion from 'Node *'
to 'Node **' for 1st argument
void copyTree_helper(Node **destination,const Node *source)
非常感谢任何帮助或解释,帮助我弄清楚这一切。干杯!
问题是你应该传递&root
,而不是&*root
- *root
是一个Node
,而不是一个Node*
。
不过,这在功能上写得更好:
Node* copyTree_helper(const Node *source)
{
if(source == nullptr)
{
return nullptr;
}
Node* result = new Node;
result->data = source->data;
result->left = copyTree_helper(source->left);
result->right = copyTree_helper(source->right);
return result;
}
BinarySearchTree::BinarySearchTree(const BinarySearchTree &rhs)
: root(copyTree_helper(rhs.root))
{
}
或者,如果您将合适的构造函数添加到Node
:
Node* copyTree_helper(const Node *source)
{
return source == nullptr
? nullptr
: new Node(source->data,
copyTree_helper(source->left),
copyTree_helper(source->right));
}
相关文章:
- C++取消引用指针.为什么会发生变化
- 使用取消引用的指针的多态性会产生意外的结果.为什么?
- 取消引用运算符不能重载
- 在他自己的方法中,有可能将一个对象取消引用到另一个对象吗
- C++ 关于指针取消引用的技术问题
- 没有取消引用/解包对象的标准方法?
- 列表 iter 不取消引用 使用列表进行插入排序
- 在这个函数中是有缺陷的,因为取消引用 null 是无效的,所以我想更改代码
- 取消引用结束指针到数组类型的一个
- 取消引用向量时出现问题
- 取消引用指向整数的指针时获得不同的结果
- C++:取消引用十六进制值,有点语法问题
- C/C++ 取消引用错误:在空检查之前取消引用
- 取消引用后C++空测试
- 立即取消引用unique_ptr
- 如何在不使用临时变量的情况下取消引用返回指针的函数的返回值?
- 取消引用 void 指针以将值分配给结构
- boost_multi_index迭代器取消引用给出常量
- 矢量迭代器不能与 std::shared_ptr<> 取消引用
- C++我们可以取消引用此指针吗?如果是这样,那么如何,如果不是,那为什么?