/// <summary> /// Balances a subtree to comply with AVL property. /// </summary> /// <param name="node">The root node of the subtree.</param>0 protected void Balance(AvlNode node) { while (node != null) { node.Balance = AvlNode.GetBalance(node); Int32 newHeight = AvlNode.GetHeight(node); if (newHeight == node.Height) { return; } node.Height = newHeight; switch (node.Balance) { case -2: switch ((node.LeftChild as AvlNode).Balance) { case 0: // --,= case -1: // --,- node = RotateRight(node) as AvlNode; (node.RightChild as AvlNode).Height = AvlNode.GetHeight(node.RightChild); (node.RightChild as AvlNode).Balance = AvlNode.GetBalance(node.RightChild); node.Height = AvlNode.GetHeight(node); node.Balance = AvlNode.GetBalance(node); break; case 1: // --,+ RotateLeft(node.LeftChild); node = RotateRight(node) as AvlNode; (node.LeftChild as AvlNode).Height = AvlNode.GetHeight(node.LeftChild); (node.LeftChild as AvlNode).Balance = AvlNode.GetBalance(node.LeftChild); (node.RightChild as AvlNode).Height = AvlNode.GetHeight(node.RightChild); (node.RightChild as AvlNode).Balance = AvlNode.GetBalance(node.RightChild); node.Height = AvlNode.GetHeight(node); node.Balance = AvlNode.GetBalance(node); break; } break; case 2: switch ((node.RightChild as AvlNode).Balance) { case 0: // ++,= case 1: // ++,+ node = RotateLeft(node) as AvlNode; (node.LeftChild as AvlNode).Height = AvlNode.GetHeight(node.LeftChild); (node.LeftChild as AvlNode).Balance = AvlNode.GetBalance(node.LeftChild); node.Height = AvlNode.GetHeight(node); node.Balance = AvlNode.GetBalance(node); break; case -1: // ++,- RotateRight(node.RightChild); node = RotateLeft(node) as AvlNode; (node.LeftChild as AvlNode).Height = AvlNode.GetHeight(node.LeftChild); (node.LeftChild as AvlNode).Balance = AvlNode.GetBalance(node.LeftChild); (node.RightChild as AvlNode).Height = AvlNode.GetHeight(node.RightChild); (node.RightChild as AvlNode).Balance = AvlNode.GetBalance(node.RightChild); node.Height = AvlNode.GetHeight(node); node.Balance = AvlNode.GetBalance(node); break; } break; } node = node.Parent as AvlNode; } }
private int Height(AvlNode node) { return(node == null ? -1 : node.GetHeight()); }