Я выставляю вам код для использования AVL tree, который я разработал. Метод для вставки, метод avlinsert
приведен ниже. Я разработал этот код на бумаге, и он не протестирован, но я надеюсь, что это сработает. Основная проблема, которую я хочу обсудить, заключается в том, что фактор баланса узлов сначала просматривает код. Таким образом, станет ясно, что я пытаюсь спросить. Так вот код:Вставить метод дерева AVL?
treeNode* avlinsert(treeNode* tree, int info)
{
treeNode* newNode=new treeNode;
newNode->setinfo(info);
newNode->setbalance(0);
treeNode* p,*q;
bool duplicate=false;
p=q=tree;
stack s; //I have made this stack already and now I am using it here.
//Now the the while loop block will check for duplicate nodes, this block prevents the duplicate insertion.
while (q!=NULL)
{
p=q;
if (info < p -> getinfo())
q=p->getleft();
else if (info>p->getinfo())
q=p->getright();
else
{
duplicate=true;
cout<<"Trying to insert duplicate";
break;
}
}//while loop ended.
//Now checking for duplicates.
if (duplicate)
return tree;
p=q=tree;
//Now below is the main block of while loop which calculates the balance factors of nodes and helps in inserting nodes at proper positions.
while (q!=NULL)
{
p=q;
if (info < p -> getinfo())
{
p->setbalance(p -> getbalance()+1);
s.push(p);//pushing into stack
q=p->getleft();
}
else if (info > p -> getinfo())
{
p->setbalance(p->getbalance()-1);
q=p->getright();
}
}//while loop ended
//Now the below code block will actually inserts nodes.
if (info < p -> getinfo())
p->setleft(newNode);
else if (info > p -> getinfo())
p->setright(newNode);
//After this insertion we need to check the balance factor of the nodesand perform the approprite rotations.
while (!s.isempty())
{
treeNode node;
node=s.pop();
int balance;
balance=node.getbalance();
if (balance==2)
{
s.Makeempty(); // We have found the node whoes balance factor is violating avl condition so we don't need other nodes in the stack, therefor we are making stack empty.
treeNode* k1,*k3;
k1=&node; //This is the node whoes balance factor is violating AVL condition.
k3=&(k1 -> getleft()); //Root of the left subtree of k1.
//Identifying the cases of insertion
if (info < k3 -> getinfo()) //This is the case of insertion in left subtree of left child of k1 here we need single right rotation.
root=Rightrotation(k1); //Here root is the private data member.
//Next case is the insertion in right subtree of left child of k1.
if (info > k3 ->getinfo())
root=LeftRightrotation(k1);
}//end of if statement.
}//while loop ended
Это не весь код, но этого достаточно, чтобы показать, что я пытаюсь сделать. Вы видели в этом коде, что я устанавливаю коэффициент баланса узлов во время вставки (второй в блоке цикла). Хорошо, это нормально. Но после этой вставки мне нужно выполнить повороты. У меня также есть код поворота, но главная проблема заключается в том, когда узлы повернуты, тогда мне нужно сбросить коэффициенты баланса узлов в коде вращения. Это проблема со мной. Как я могу это сделать? И какой будет фрагмент кода?
@Zia ур Рахман: Я не буду редактировать код. Я уже делал это четыре раза, и вы редактируете его снова.x- ( –
+ 1 для комментариев ур, lol !! – Krunal
@ Zia ur Rahman: Вы говорите, что вам нужно сбросить коэффициенты баланса в коде вращения, но вы не дадите нам код поворота. Если вы просто хотите обновить коэффициенты баланса всего дерева, проверьте мой ответ, иначе обновите свой вопрос, чтобы мы могли помочь вам! @Prasoon: +1 от меня тоже! hehehe :) – Alex