AVLTree-restructure

# AVLTree-restructure - void AVLTree:restructure(AVLNode*n...

This preview shows pages 1–3. Sign up to view the full content.

void AVLTree::restructure(AVLNode *n) { // balance tree starting at node n // Find "z" that is the first unbalanced node starting at "z". AVLNode *z = n->parent; while(z != NULL) { // while w not reach root // Find parent of unbalanced tree int hleft = 0; if(z->left != NULL) { hleft = z->left->height; } int hright = 0; // height right child if(z->right != NULL) { hright = z->right->height; } int hdiff = hleft - hright; if(hdiff < 0) hdiff = -hdiff; // make diff absolute // Check if z is unbalanced if(hdiff <= 1) { // z is balanced TO BE CONTINUED... // Recompute height of z just in case it was modified with a rotation previously. if(hleft>hright) { z->height = 1+hleft; } else { z->height = 1+ hright; } // test if z is unbalanced if(diff <= 1) { // z is balanced z = z->parent; continue;

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
} // At this point z is parent of an unbalanced subtree // Find y, y is the child of z that has highest height. AVLNode *y = NULL; int maxh = 0; if(z->left != NULL) { y = z->left; maxh = y->height; } if(z->right != NULL && maxh < z->right->height) { y = z->right; maxh = y->height; } // Find x. x is the child of z with highest height AVLNode *x = NULL; maxh = 0; if(y->left != NULL) { x = y->left; maxh = x->height; } if(y->right != NULL && maxh < y->right->height)
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

### What students are saying

• As a current student on this bumpy collegiate pathway, I stumbled upon Course Hero, where I can find study resources for nearly all my courses, get online help from tutors 24/7, and even share my old projects, papers, and lecture notes with other students.

Kiran Temple University Fox School of Business ‘17, Course Hero Intern

• I cannot even describe how much Course Hero helped me this summer. It’s truly become something I can always rely on and help me. In the end, I was not only able to survive summer classes, but I was able to thrive thanks to Course Hero.

Dana University of Pennsylvania ‘17, Course Hero Intern

• The ability to access any university’s resources through Course Hero proved invaluable in my case. I was behind on Tulane coursework and actually used UCLA’s materials to help me move forward and get everything together on time.

Jill Tulane University ‘16, Course Hero Intern