2016-12-11 4 views
0

私は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; 

私はmain.cppにファイル内MyBST tree1というの値を変更しようとしているが、私は試してみてください時に値が唯一私が使用した関数の内部で変化していること、およびていませんよ。どのようにしてノードを正確に呼び出して、ノードがまったく同じになるようにする必要があります。

答えて

0

これは非常に基本的な間違いでした。正直なところ、私は正しく値を返さなかったのです。

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; 
} 

のノードのすべての文字列を最新のものに更新されたように、私は、リターン機能がありませんでしたこれは私がそれを固定する方法です。

関連する問題