我正在研究AVL树。我想我已经拥有了所有的旋转功能。我有一个rotateleft,rotateright,rotateleftright和rotaterightleft功能。它们都以节点为参数。我不知道要传递给这些参数的节点。你可以看看我的AVL树重新平衡函数,并告诉我是否正确,以及我需要传递给每个函数。到目前为止,我有根或顶级节点,但我认为我错了。我怎么知道我需要传递给这些函数?C++中的AVL树重新平衡
下面是函数:
void BinaryTree::rebalance(Node *N)
{
int count = 1;
if((N->getLeft()->getHeight()) > (N->getRight()->getHeight() + 1))
{
if(N->getLeft()->getLeft()->getHeight() > N->getLeft()->getRight()->getHeight())
{
rotateRight(root);
recalculate(root, count);
}
else
{
rotateLeftRight(root);
recalculate(root, count);
}
}
else if(N->getRight()->getHeight()> N->getLeft()->getHeight() + 1)
{
if(N->getRight()->getRight()->getHeight() > N->getRight()->getLeft()->getHeight())
{
rotateLeft(root);
recalculate(root, count);
}
else
{
rotateRightLeft(root);
recalculate(root, count);
}
}
}
这里是我的旋转,左右改变
Node* BinaryTree::rotateLeftRight(Node *N)
{
Node *newNode = new Node();//declares a new Node
newNode = N->getLeft();//sets the node
N->setLeft(rotateLeft(newNode->getLeft());//sets the left subtree
recalculate(root);//recalculates the height
root->setHeight(NULL);//sets the height of the root node
return rotateRight(N);//retuns the tree rotated right
}
,这里是我的左右旋转功能:
Node* BinaryTree::rotateLeft(Node *N)
{
Node *newNode = new Node();//declares a new node
newNode = N->getRight();//sets the new node to the right child of N
N->setRight(newNode->getLeft());//sets the right of N equal to new nodes left child
newNode->setLeft(N);//sets the left child of the new node to N
return newNode;//retuns the newNode
}
如果我有树50 20 10和15我通过什么传递给这些函数来重新平衡树?
这似乎更适合[codereview](http://codereview.stackexchange.com)。 – 2013-04-08 20:06:06
如果是为了别的什么,但家庭作业,那么不要打扰。 RB树更有效率。 – 2013-04-08 20:08:44
它是为homeowrk,如果您的代码正在工作,则im卡住 – compprog254 2013-04-08 20:10:48