所以我有一个BST数据结构,我想创建一个找到父节点并旋转节点的函数。我已成功完成此操作,但是,它没有正确更新树中的值,它只在函数内部进行。
MyBST.cpp:
节点结构:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let jsonObject = jsonData[indexPath.row]
let keyCount = jsonObject.keys.count
if keyCount == 3 {
3Pic.leftNameLabel.text = "Name"
3Pic.leftPositionLabel.text = "Position"
3Pic.leftImageView.image = UIImage(named: "icon")
3Pic.MidddleNameLabel.text = "Name"
3Pic.MiddlePositionLabel.text = "Position"
3Pic.MiddleImageView.image = UIImage(named: "icon")
3Pic.RightNameLabel.text = "Name"
3Pic.RightPositionLabel.text = "Position"
3Pic.RightImageView.image = UIImage(named: "icon")
} else {
2Pic.leftNameLabel.text = "Name"
2Pic.leftPositionLabel.text = "Position"
2Pic.leftImageView.image = UIImage(named: "icon_about")
2Pic.rightNameLabel.text = "Name"
2Pic.rightPositionLabel.text = "Position"
2Pic.rightImageView.image = UIImage(named: "icon")
}
return cell
}
旋转功能:
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
};
findParentRotate函数:
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;
}
main.cpp中:
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;
}
我试图更改MyBST tree1的值,但是当我尝试这样做时,值只会在我使用的函数内部更改,而不是在main.cpp文件中。我应该如何正确调用指针,以便节点保持不变。
答案 0 :(得分: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;
}
我错过了返回函数,因此所有节点字符串都更新为最新的节点。