Here is my splay function:
template <class WA>
void SplayTree<WA>::Do_Splay(SplayNODE<WA> *temp) {
if (temp==root) { return; }
else if (root->left==temp || root->right==temp) {
if (root->left==temp) {
Zig(root); }
else if (root->right==temp) {
Zag(root); }
}
else {
SplayNODE<WA> *father = findfather(temp, root);
SplayNODE<WA> *grandfather = findfather(father, root);
if ( grandfather->left == father) {
if(father->left == temp) { cout<<"\tZig(father)---Zag(grandfather)";
Zig(grandfather);
Zig(father);
}
else if ( father->right == temp ) { cout<<"\tZig(father)---Zag(grandfather)";
Zig(father);
Zag(grandfather);
}
}
if (grandfather->right == father) {
if(father->right == temp)
{ cout<<"\tZag(grandfather)---Zag(father)";
Zag(grandfather);
Zag(father);
}
else if (father->left == temp)
{ cout<<"\tZag(father)---Zig(grandfather)";
Zag(father);
Zig(grandfather);
}
}
}
}
Following are methods of Zig (Single Rotate Left) & Zag (Single Rotate Right).
template <class WA>
void SplayTree<WA>::Zig(SplayNODE<WA> * & k2) {
SplayNODE<WA> *k1 = k2->left; k2->left = k1->right; k1->right = k2; k2 = k1; }
template <class WA>
void SplayTree<WA>::Zag(SplayNODE<WA> * & k2)
{
SplayNODE<WA> *k1 = k2->right; k2->right = k1->left; k1->left = k2; k2 = k1; }
& Here is my f** problem.
For start, Im splaying in search function only. i.e. splay if a node with specific *key* is found.
My Search Function:
template <class WA>
SplayNODE<WA>* SplayTree<WA>::search(SplayNODE<WA> *temp, WA value) {
SplayNODE<WA> *to_searched = 0; if (temp!=0) {
if (temp->key==value) {
to_searched = temp; Do_Splay(temp); }
if (to_searched==0) { to_searched = search(temp->left, value); } if (to_searched==0) { to_searched = search(temp->right, value); } }
return to_searched; }
Following work fine in case if a node is a child of root.
- Zig Single
- Zag Single
But as soon as we go a single node down, the problem starts. I can't execute any of these things successfully.
- Zig Zig
- Zig Zag
- Zag Zag
- Zag Zig
Here is the Sample tree.
(Zig Zig Case)
20
/ \
10 25
/ \
5 15
When 5 is searched, answer should be.
5
\
10
\
20
/ \
15 25
But my output becomes:
20
/ \
15 25
Can't figure out whats the problem. Dry run-ed this thing 100 times but. :(
Any & all help is appreciated. Thanks in Advance