public static AVLTree Initialize(int[] keys) { AVLTree result = new AVLTree(keys[0]); for (int i = 1; i < keys.Length; i++) result = Grow(result, keys[i]); return result; }
public AVLTree(int key) { this.key = key; left = null; right = null; height = 1; }
private AVLTree RotateLeft() { AVLTree result = this.right; this.right = result.left; result.left = this; this.FixHeight(); result.FixHeight(); return result; }
public static AVLTree Grow(AVLTree tree, int key) { if (tree == null) return new AVLTree(key); if (key < tree.key) tree.left = Grow(tree.left, key); else tree.right = Grow(tree.right, key); return tree.Balance(); }
private AVLTree Balance() { this.FixHeight(); if (this.GetBalanceFactor() == 2) { if (this.right.GetBalanceFactor() < 0) this.right = this.right.RotateRight(); return this.RotateLeft(); } if (this.GetBalanceFactor() == -2) { if (this.left.GetBalanceFactor() > 0) this.left = this.left.RotateLeft(); return this.RotateRight(); } return this; }
private static int GetHeight(AVLTree tree) { return((tree == null) ? 0 : tree.height); }
public bool Search(AVLTree tree, int key) { if (tree == null) return false; if (tree.key > key) return Search(tree.left, key); if (tree.key < key) return Search(tree.right, key); else return true; }
private static int GetHeight(AVLTree tree) { return (tree == null) ? 0 : tree.height; }
bool IsLeftRight(T item, AVLTree <T> node) { return(Comparer.Compare(item, node._left.Value).IsFirstMore); }
bool IsLeftLeft(T item, AVLTree <T> node) { return(Comparer.Compare(item, node._left.Value).IsFirstLess); }
void SetHeight(AVLTree <T> node) { node.Height = 1 + Math.Max(GetHeight(node._left), GetHeight(node._right)); }