/// <summary> Internal method to find an item in a subtree.</summary> /// <param name="x">is item to search for. /// </param> /// <param name="t">the node that roots the tree. /// </param> /// <returns> node containing the matched item. /// </returns> private AvlNode find(Comparable x, AvlNode t) { while (t != null) { if (x.compareTo(t.element) < 0) { t = t.left; } else if (x.compareTo(t.element) > 0) { t = t.right; } else { return(t); // Match } } return(null); // No match }
/// <summary> Internal method to insert into a subtree.</summary> /// <param name="x">the item to insert. /// </param> /// <param name="t">the node that roots the tree. /// </param> /// <returns> the new root. /// </returns> private AvlNode insert(Comparable x, AvlNode t) { if (t == null) { t = new AvlNode(x, null, null); } else if (x.compareTo(t.element) < 0) { t.left = insert(x, t.left); if (height(t.left) - height(t.right) == 2) { if (x.compareTo(t.left.element) < 0) { t = rotateWithLeftChild(t); } else { t = doubleWithLeftChild(t); } } } else if (x.compareTo(t.element) > 0) { t.right = insert(x, t.right); if (height(t.right) - height(t.left) == 2) { if (x.compareTo(t.right.element) > 0) { t = rotateWithRightChild(t); } else { t = doubleWithRightChild(t); } } } else { } // Duplicate; do nothing t.height = max(height(t.left), height(t.right)) + 1; return(t); }
/// <summary> Double rotate binary tree node: first right child /// with its left child; then node k1 with new right child. /// For AVL trees, this is a double rotation for case 3. /// Update heights, then return new root. /// </summary> private static AvlNode doubleWithRightChild(AvlNode k1) { k1.right = rotateWithLeftChild(k1.right); return(rotateWithRightChild(k1)); }
/// <summary> Double rotate binary tree node: first left child /// with its right child; then node k3 with new left child. /// For AVL trees, this is a double rotation for case 2. /// Update heights, then return new root. /// </summary> private static AvlNode doubleWithLeftChild(AvlNode k3) { k3.left = rotateWithRightChild(k3.left); return(rotateWithLeftChild(k3)); }
/// <summary> Return the height of node t, or -1, if null.</summary> private static int height(AvlNode t) { return(t == null?-1:t.height); }
/// <summary> Internal method to get element field.</summary> /// <param name="t">the node. /// </param> /// <returns> the element field or null if t is null. /// </returns> private Comparable elementAt(AvlNode t) { return(t == null?null:t.element); }