【发布时间】:2017-04-26 05:37:15
【问题描述】:
所以我有一个 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 文件中。我应该如何正确调用指针以使节点始终保持不变。
【问题讨论】:
标签: c++ pointers recursion struct binary-search-tree