/* AVL rotations pseudo-code * slightly modified from Ford and Topp * */ Node singleRight ( Node p ) { Node lc = p.left; p.left = lc.right; lc.right = p p.height = max ( height (p.left), height(p.right) ) + 1; lc.height = max ( height(lc.left), lc.height) + 1; return lc; } Node singleLeft ( Node p ) { Node rc = p.right; p.right = rc.left; rc.left = p; p.height = max ( height (p.left), height (p.right) ) + 1; rc.height = max (height(rc.right), rc.height) + 1; return rc; } Node doubleRight (Node p) { p.left = singleLeft(p.left); return singleRight(p); } Node doubleLeft (Node p) { p.right = singleRight(p.right); return singleLeft(p); } Node addNode (Node t, int item) { if (t == null) t = new Node(item); else if ( (item < t.value) { t.left = addNode(t.left, item); if (height(t.left) - height(t.right) == 2 ) if (item < t.left.value) t = singleRight(t); else t = doubleRight(t); } else if (t.value < item) { t.right = addNode (t.right, item); if (height(t.left) - height(t.right) == -2) if (t.right.value < item) t = singleLeft(t); else t = doubleLeft(t); } else // duplicate -- throw IllegalStateException throw new IllegalStateException(); t.height = max (height(t.lef), height(t.right) ) + 1; return t; } boolean add (int item) { try { root = addNode (root, item); } catch (IllegalStateException ise) { return false; } // increment tree size treeSize++; // added a node to tree return true; }