我正在研究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