public override void remove(T val) { AVLTreeNode <T> parent; AVLTreeNode <T> current = searchWithParent(val, out parent); if (current == null) { return; } //Удаление листа if (current.left == null && current.right == null) { if (parent.left == current) { parent.left = null; } else { parent.right = null; } rebalance(parent); return; } //Удаляемый элемент имеет одного потомка if (current.left == null || current.right == null) { if (current.left == null) { if (parent == null) { root = current.right; } else { if (parent.left == current) { parent.left = current.right; } else { parent.right = current.right; } } } else { if (parent == null) { root = current.left; } else { if (parent.left == current) { parent.left = current.left; } else { parent.right = current.left; } } } rebalance(parent); return; } //Удаляемый элемент имеет двух потомков if (current.left != null && current.right != null) { AVLTreeNode <T> binaryTreeNode = current.left; AVLTreeNode <T> parentBinaryTreeNode = current; while (binaryTreeNode.right != null) { parentBinaryTreeNode = binaryTreeNode; binaryTreeNode = binaryTreeNode.right; } binaryTreeNode.right = current.right; if (parentBinaryTreeNode != current) { parentBinaryTreeNode.right = binaryTreeNode.left; binaryTreeNode.left = current.left == binaryTreeNode ? null : current.left; } if (parent == null) { root = binaryTreeNode; } else { if (parent.left == current) { parent.left = binaryTreeNode; } else { parent.right = binaryTreeNode; } } rebalance(binaryTreeNode); } }