Beispiel #1
0
        NodeAVL <T> rotateLeft(NodeAVL <T> node) // левый поворот вокруг node
        {
            NodeAVL <T> newNode = node.right;

            if (node.Equals(root))
            {
                newNode.parent = null;
                root           = newNode;
            }
            else
            {
                if (isLeft(node))
                {
                    node.parent.left = newNode;
                }
                else
                {
                    node.parent.right = newNode;
                }
            }

            node.right     = newNode.left;
            newNode.left   = node;
            newNode.parent = node.parent;
            node.parent    = newNode;

            fixHeight(node);
            fixHeight(newNode);
            return(newNode);
        }
Beispiel #2
0
        public NodeAVL <T> insert(T key)//вставка элемента
        {
            NodeAVL <T> node = (NodeAVL <T>)root;

            insert(key, node);
            return(node);
        }
Beispiel #3
0
 public NodeAVL(T val, NodeAVL <T> par = null)
 {
     this.key    = val;
     this.height = 1;
     this.parent = par;
     this.left   = null;
     this.right  = null;
 }
Beispiel #4
0
 private NodeAVL <T> insert(T key, NodeAVL <T> node, NodeAVL <T> parent = null)
 {
     if (node == null)
     {
         node = new NodeAVL <T>(key, parent);
     }
     else if (key.CompareTo(node.key) < 0)
     {
         balance(node.left = insert(key, (NodeAVL <T>)node.left, node));
     }
     else
     {
         balance(node.right = insert(key, (NodeAVL <T>)node.right, node));
     }
     return(node);
 }
Beispiel #5
0
 NodeAVL <T> balance(NodeAVL <T> node) // балансировка узла
 {
     fixHeight(node);
     if (balanceFactor(node) == 2)
     {
         if (balanceFactor(node.right) < 0)
         {
             rotateRight(node.right);
         }
         rotateLeft(node);
     }
     else if (balanceFactor(node) == -2)
     {
         if (balanceFactor(node.left) > 0)
         {
             node.left = rotateLeft(node.left);
         }
         rotateRight(node);
     }
     return(node);
 }
Beispiel #6
0
 private void fixHeight(NodeAVL <T> node)
 {
     node.height = (height(node.left) > height(node.right) ? height(node.left) : height(node.right)) + 1;
 }
Beispiel #7
0
 private int balanceFactor(NodeAVL <T> node)
 {
     return(height(node.right) - height(node.left));
 }
Beispiel #8
0
 private int height(NodeAVL <T> node)
 {
     return(node != null ? node.height : 0);
 }
Beispiel #9
0
 public AVLTree(T val)
 {
     root = new NodeAVL <T>(val);
 }