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というの値を変更しようとしているが、私は試してみてください時に値が唯一私が使用した関数の内部で変化していること、およびていませんよ。どのようにしてノードを正確に呼び出して、ノードがまったく同じになるようにする必要があります。