/// <summary> /// Balances node. /// </summary> /// <returns> /// The balance. /// </returns> public bool Balance() { if (this.Left != null) { this.Left.Balance(); } if (this.Right != null) { this.Right.Balance(); } this.UpdateHeight(); int leftHeight = 0; int rightHeight = 0; if (this.Left != null) { leftHeight = this.Left.Height; } if (this.Right != null) { rightHeight = this.Right.Height; } if (leftHeight - rightHeight > 1) { // right rotation AVLTreeNode <T> z = this; AVLTreeNode <T> y = this.Left; AVLTreeNode <T> b = this.Left.Right; bool zIsleftNode = z.Parent != null && ((AVLTreeNode <T>)z.Parent).Left == this; z.Left = b; if (b != null) { b.Parent = z; } y.Right = z; if (y != null) { y.Parent = z.Parent; if (y.Parent != null) { if (zIsleftNode) { ((AVLTreeNode <T>)y.Parent).Left = y; } else { ((AVLTreeNode <T>)y.Parent).Right = y; } } } z.Parent = y; if (b != null) { b.UpdateHeight(); } if (z != null) { z.UpdateHeight(); } if (y != null) { y.UpdateHeight(); } return(true); } if (rightHeight - leftHeight > 1) { // left rotation AVLTreeNode <T> z = this; AVLTreeNode <T> y = this.Right; AVLTreeNode <T> b = this.Right.Left; bool zIsleftNode = z.Parent != null && ((AVLTreeNode <T>)z.Parent).Left == this; z.Right = b; if (b != null) { b.Parent = z; } y.Left = z; if (y != null) { y.Parent = z.Parent; if (y.Parent != null) { if (zIsleftNode) { ((AVLTreeNode <T>)y.Parent).Left = y; } else { ((AVLTreeNode <T>)y.Parent).Right = y; } } } z.Parent = y; if (b != null) { b.UpdateHeight(); } if (z != null) { z.UpdateHeight(); } if (y != null) { y.UpdateHeight(); } return(true); } return(false); }