通过递归正确传递指针的值

Passing the value of a pointer correctly through recursion

本文关键字:指针 递归      更新时间:2023-10-16

所以我有一个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;
}

我缺少返回函数,因此所有节点的字符串已更新为最新的节点。