TheAlgorithms/C-Sharp · error · ArgumentException

Key " " already exists in tree!

Error message

Key "{key}" already exists in tree!

What it means

BinarySearchTree.Add throws ArgumentException when the key being added already exists in the tree. The recursive insert reaches the 'Key is already in tree' branch when comparison finds an exact match, and since this BST enforces unique keys, the insert is rejected instead of overwriting the node's value.

Solutions

  1. Check Contains(key) before Add and skip or update the existing node
  2. Deduplicate input before inserting (Distinct on keys)
  3. Catch ArgumentException with Message.Contains("already exists") when duplicates are expected
  4. If overwrite semantics are needed, write an Update method or use Dictionary instead

Example fix

// before
bst.Add(key, value); // throws on duplicate
// after
if (!bst.Contains(key))
{
    bst.Add(key, value);
}
else
{
    bst.Update(key, value); // or skip
}
Defensive patterns

Strategy: validation

Validate before calling

if (!bst.Contains(key)) bst.Add(key, value);

Type guard

null

Try / catch

try { bst.Add(key, value); } catch (ArgumentException ex) when (ex.Message.Contains("already exists")) { /* duplicate handling */ }

Prevention

When it happens

Trigger: Calling BinarySearchTree.Add(key, value) with a duplicate key; also when a custom comparer makes two distinct keys compare equal (e.g., case-insensitive strings).

Common situations: Re-adding an element after failed removal; duplicate IDs in input data; treating the BST as a map with overwrite semantics when it behaves as a set; recursive Add wrapper re-invoked with the same key.

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/61695fc0725a9fc8. Report an issue: GitHub.

Appendix: source

Thrown at DataStructures/BinarySearchTree/BinarySearchTree.cs:191

            }
        }
        else if (compareResult < 0)
        {
            if (node.Right is not null)
            {
                Add(node.Right, key);
            }
            else
            {
                var newNode = new BinarySearchTreeNode<TKey>(key);
                node.Right = newNode;
            }
        }

        // Key is already in tree.
        else
        {
            throw new ArgumentException($"""Key "{key}" already exists in tree!""");
        }
    }

    /// <summary>
    ///     Removes a node with the specified key from the BST.
    /// </summary>
    /// <param name="parent">The parent node of <paramref name="node" />.</param>
    /// <param name="node">The node to check/search from.</param>
    /// <param name="key">The key to remove.</param>
    /// <returns>true if the operation was successful, false otherwise.</returns>
    /// <remarks>
    ///     Removing a node from the BST can be split into three cases:
    ///     <br></br>
    ///     0. The node to be removed has no children. In this case, the node can just be removed from the tree.
    ///     <br></br>
    ///     1. The node to be removed has one child. In this case, the node's child is moved to the node's parent,
    ///     then the node is removed from the tree.
    ///     <br></br>

View on GitHub (pinned to 96e2905cab)