Esempio n. 1
0
        private AvlNode RightRotate(AvlNode root)
        {
            var newRoot = root.GetLeftChild();

            root.SetLeftChild(newRoot.GetRightChild());
            newRoot.SetRightChild(root);

            SetHeight(root);
            SetHeight(newRoot);

            return(newRoot);
        }
Esempio n. 2
0
 private AvlNode Balance(AvlNode root)
 {
     if (IsLeftHeavy(root))
     {
         if (BalanceFactor(root.GetLeftChild()) < 0)
         {
             //Console.WriteLine("Left Rotate " + root.GetLeftChild().GetValue());
             root.SetLeftChild(LeftRotate(root.GetLeftChild()));
         }
         //Console.WriteLine("Right Rotate" + root.GetValue());
         return(RightRotate(root));
     }
     if (IsRightHeavy(root))
     {
         if (BalanceFactor(root.GetRightChild()) > 0)
         {
             root.SetRightChild(RightRotate(root.GetRightChild()));
             //Console.WriteLine("Right Rotate " + root.GetRightChild().GetValue());
         }
         //Console.WriteLine("Left Rotate " + root.GetValue());
         return(LeftRotate(root));
     }
     return(root);
 }
Esempio n. 3
0
        private AvlNode Insert(AvlNode root, int value)
        {
            if (root == null)
            {
                return(new AvlNode(value));
            }

            if (value > root.GetValue())
            {
                root.SetRightChild(Insert(root.GetRightChild(), value));
            }
            else
            {
                root.SetLeftChild(Insert(root.GetLeftChild(), value));
            }

            SetHeight(root);

            return(Balance(root));
        }
Esempio n. 4
0
 private int BalanceFactor(AvlNode node)
 {
     return(node == null ? 0 : Height(node.GetLeftChild()) - Height(node.GetRightChild()));
 }
Esempio n. 5
0
 private void SetHeight(AvlNode node)
 {
     node.SetHeight(Math.Max(
                        Height(node.GetLeftChild()),
                        Height(node.GetRightChild())) + 1);
 }