private AvlNode LeftRotate(AvlNode root) { var newRoot = root.GetRightChild(); root.SetRightChild(newRoot.GetLeftChild()); newRoot.SetLeftChild(root); SetHeight(root); SetHeight(newRoot); return(newRoot); }
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); }
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)); }
private int BalanceFactor(AvlNode node) { return(node == null ? 0 : Height(node.GetLeftChild()) - Height(node.GetRightChild())); }
private void SetHeight(AvlNode node) { node.SetHeight(Math.Max( Height(node.GetLeftChild()), Height(node.GetRightChild())) + 1); }