I am trying to create an AVL tree, the most importation is rotation. I used my sample data but the result is wrong in the first rotation.
I think the error is that I didn't return the correct object after rotation. Please help me to look at it.
namespace AVLTree { public class AVLTree { private AvlTreeNode root; // AvlTreeNode has three fields, data, left and right. public AVLTree() { root = null; } public void Insert(int value) { Insert(value, ref root); if (!IsBanlance(root)) ReBanlance(root); } private void Insert(int element, ref AvlTreeNode node) { // blah blah } public void ReBanlance(AvlTreeNode node) { int heightDiff = GetHeight(node.left) - GetHeight(node.right); if (heightDiff > 1)//left case { if (GetHeight(node.left.left) > GetHeight(node.left.right))//left left case { RightRotation(node); } else// left right case { LeftRotation(node); RightRotation(node); } } else if (heightDiff < -1)//right case { if (GetHeight(node.right.left) > GetHeight(node.right.right))//right left case { RightRotation(node); LeftRotation(node); } else//right right case { LeftRotation(node); RightRotation(node); } } return true; } // http://en.wikipedia.org/wiki/Tree_rotation // Left Rotation of node P: // Let Q be P's right child. // Set Q to be the new root. // Set P's right child to be Q's left child. // Set Q's left child to be P. public bool LeftRotation(AvlTreeNode P) { // Define new instances AvlTreeNode Q = new AvlTreeNode(); AvlTreeNode A = new AvlTreeNode(); AvlTreeNode B = new AvlTreeNode(); AvlTreeNode C = new AvlTreeNode(); // Original tree expression Q = P.right; A = P.left; B = Q.left; C = Q.right; // Begin rotation P.left = A; P.right = B; Q.left = P; Q.right = C; return true; } // Right Rotation of node Q: // Let P be Q's left child. // Set P to be the new root. // Set Q's left child to be P's right child. // Set P's right child to be Q. public bool RightRotation(AvlTreeNode Q) { // Define new instances AvlTreeNode P = new AvlTreeNode(); AvlTreeNode A = new AvlTreeNode(); AvlTreeNode B = new AvlTreeNode(); AvlTreeNode C = new AvlTreeNode(); // Original tree expression P = Q.left; A = P.left; B = P.right; C = Q.right; // Begin rotation P.left = A; Q.right = C; Q.left = B; P.right = Q; return true; }