【发布时间】:2022-12-14 01:20:21
【问题描述】:
我想创建一个从子节点到其父节点的弱指针,但我不知道如何获取该节点。我不想更改我的所有代码以使其工作,但我不知道任何其他方式
namespace Datastructures {
// creating new tree nodes with given data and nullptr to left and right child
TreeNode::TreeNode (int data){
data_ = data;
left_child = nullptr;
right_child = nullptr;
WeakTreeNodeptr parent;
}
// returns data of the tree node
int TreeNode::get_data(){
return data_;
}
// sets data of the tree node
void TreeNode::set_data(int data){
data_ = data;
}
// sets the data of the left child of the tree node
void TreeNode::set_left_child(int data){
if (left_child == nullptr) // if the left child does not exist then create one
{
left_child = std::make_shared<TreeNode>(data);
}
else // if a left child exists then change the data to the given data
{
left_child->data_ = data;
}
}
// sets the data of the right child of the tree node
void TreeNode::set_right_child(int data){
if (right_child == nullptr) // if the right child does not exist then create one
{
right_child = std::make_shared<TreeNode>(data);
}
else //if a right child exists then change the data to the given data
{
right_child->data_ = data;
}
}
}
【问题讨论】:
-
获取什么节点?请提供minimal reproducible example,说明您尝试过的内容以及遇到的问题。
-
获取父节点指针没有神奇的方法,您需要将其存储在 TreeNode 类中。因此,您需要更改 TreeNode 类以添加该成员变量。完成后,您需要在构造函数中初始化该值,或将 set_parent_node 方法添加到 TreeNode(或两者)。话虽如此,许多二叉树节点算法不需要知道父节点。所以你可能在那里有一些灵活性。
标签: c++ binary-tree weak-ptr