TheAlgorithms/C-Sharp · error · ArgumentException

Key " " already exists in AVL tree.

Error message

Key "{key}" already exists in AVL tree.

What it means

AVLTree.Add throws ArgumentException when the key being inserted compares equal to an existing key under the tree's comparer. AVL trees enforce unique keys to keep the balance invariant well-defined, so a duplicate insert is rejected with a message naming the key. Unlike AATree.Add, this exception carries no nameof parameter argument.

Solutions

  1. Check Contains(key) before Add
  2. Catch ArgumentException and skip or log the duplicate
  3. Deduplicate input by the same comparer before inserting
  4. Switch to a multimap-style structure if duplicate keys must be stored

Example fix

// before
avl.Add(key);
// after
try { avl.Add(key); } catch (ArgumentException) { /* key already present - skip */ }
Defensive patterns

Strategy: validation

Validate before calling

if (avlTree.Contains(key)) { /* skip or update */ } else { avlTree.Add(key); }

Type guard

bool canInsert(AVLTree<TKey,TValue> t, TKey key) => !t.Contains(key);

Try / catch

try { avlTree.Add(key); } catch (ArgumentException ex) when (ex.Message.Contains("already exists")) { /* duplicate - handle */ }

Prevention

When it happens

Trigger: Calling Add(key) with a key already present per the comparer; recursive self-call Add(node, key) hitting the equal-key branch; inserting duplicate entries from a batch.

Common situations: Loading records with repeated IDs; case-insensitive comparers collapsing keys thought distinct; replaying an operation log that re-inserts existing keys.

Understand the failure class

Background: "already exists" / EEXIST / FileAlreadyExistsException: what the 'file already exists' error means and how to fix it — this error's family across 37 libraries.

Related errors


AI-assisted analysis of TheAlgorithms/C-Sharp@96e2905cab (2026-09-13). Data as JSON: /api/errors/75c91b977191fcdd. Report an issue: GitHub.

Appendix: source

Thrown at DataStructures/AVLTree/AVLTree.cs:360

            {
                node.Left = Add(node.Left, key);
            }
        }
        else if (compareResult > 0)
        {
            if (node.Right is null)
            {
                var newNode = new AvlTreeNode<TKey>(key);
                node.Right = newNode;
            }
            else
            {
                node.Right = Add(node.Right, key);
            }
        }
        else
        {
            throw new ArgumentException($"""Key "{key}" already exists in AVL tree.""");
        }

        // Check all of the new node's ancestors for imbalance and perform
        // necessary rotations
        node.UpdateBalanceFactor();

        return Rebalance(node);
    }

    /// <summary>
    ///     Recursive function to remove node from tree.
    /// </summary>
    /// <param name="node">Node to check for key.</param>
    /// <param name="key">Key value to remove.</param>
    /// <returns>New node with key removed.</returns>
    private AvlTreeNode<TKey>? Remove(AvlTreeNode<TKey>? node, TKey key)
    {
        if (node == null)

View on GitHub (pinned to 96e2905cab)