通过递归正确传递指针的值
Passing the value of a pointer correctly through recursion
所以我有一个BST数据结构,我想创建一个函数,可以找到父,并在其中旋转节点。但是,我已经成功地完成了此操作,但是,它无法正确更新树中的值,它只能在函数内完成。
mybst.cpp:
节点结构:
struct Node
{
int key; // the key stored by this node
Node *left; // the left child of this node
Node *right; // the right child of this node
};
旋转功能:
Node* MyBST::rotateRight(Node* Q)
{
Node* P = Q->left;
Q->left = P->right;
P->right = Q;
return P;
}
Node* MyBST::rotateLeft(Node* P)
{
Node* Q = P->right;
P->right = Q->left;
Q->left = P;
return Q;
}
findparentrotate函数:
Node* MyBST::findParentRotate(int num)
{
if ((root->right != nullptr && root->right->key == num) || (root->left != nullptr && root->left->key == num))
{
return root;
}
else {
findParentRotate(num, root);
}
return nullptr;
}
Node* MyBST::findParentRotate(int num, Node *n)
{
if ( (n->right != nullptr && n->right->key == num) || (n->left != nullptr && n->left->key == num) )
{
if (n->key < num)
{
n = rotateLeft(n);
cout << "The value of node inside: " << n->key << endl;
return n;
}
else {
n = rotateRight(n);
cout << "The value of node inside findParentRotate after rotation: " << n->key << endl;
return n;
}
}
else if (n->key > num)
{
findParentRotate(num, (n->left));
}
else {
findParentRotate(num, (n->right));
}
return nullptr;
}
main.cpp:
cout << "Value of node in main.cpp before rotation: " << tree1.root->left->right->left->key << endl;
tree1.findParentRotate(5);
cout << "Value of node in main.cpp after rotation: " << tree1.root->left->right->left->key << endl;
我正在尝试更改mybst tree1的值,但是当我尝试执行该值时,仅在我使用的函数内而不是在main.cpp文件中更改。我应该如何正确地称呼指针,以使节点保持不变。
所以这是一个非常基本的错误,老实说,我没有正确返回值。这就是我修复的方式:
findparentrotate函数:
void MyBST::findParentRotate(int num)
{
root = findParentRotate(num, root);
}
Node* MyBST::findParentRotate(int num, Node *n)
{
if ( (n->right != nullptr && n->right->key == num) || (n->left != nullptr && n->left->key == num) )
{
if (n->key < num)
{
n = rotateLeft(n);
return n;
}
else {
n = rotateRight(n);
return n;
}
}
else if (n->key > num)
{
n->left = findParentRotate(num, (n->left));
return n;
}
else {
n->right = findParentRotate(num, (n->right));
return n;
}
return nullptr;
}
我缺少返回函数,因此所有节点的字符串已更新为最新的节点。
相关文章:
- 在对象指针上调用 Delete 是否会递归删除其动态分配的成员
- 为什么编译器将其解析为函数指针而不是递归调用?
- 如何通过函数指针递归调用类成员函数?
- 使用双指针和递归反转链表
- 使用带有递归的指针
- 有没有办法在递归中使用指针来查找数组的最小值?
- 具有 4 个指针的节点的递归插入函数返回 null
- 共享指针中的递归,而变量在类中定义
- 尝试使用递归和指针到指针反转链表,但反转函数没有给出预期的正确输出
- 指针似乎迷失在递归算法中
- 为什么这种递归子集和算法会导致指针分配错误
- 没有指针的递归结构?(霍夫曼)
- 从 'int' 到 'int*' 的转换无效(尝试使用指针进行递归)
- 通过递归正确传递指针的值
- 通过类型C++ 的继承树递归导致此指针问题
- 是否有可能有一个指针指向由奇怪的递归模板创建的基类
- c++ 递归树 使用指针和状态机构建树
- 共享指针递归地删除递归数据结构,堆栈溢出
- c++ int数组指针递归查找质数因子
- C++传递 QDomDocument 指针递归