TheAlgorithms/C-Sharp · error · ArgumentException

Key " " already exists in tree!

Error message

Key "{key}" already exists in tree!

What it means

RedBlackTree<TKey>.Add throws ArgumentException when the insertion walk finds a node whose key compares equal to the key being inserted. The tree enforces unique keys; duplicates are rejected rather than overwritten.

Solutions

  1. Check tree.Contains(key) before calling Add.
  2. Handle duplicates explicitly: skip or update the value instead of inserting.
  3. Catch ArgumentException around Add when duplicates are expected in the input.
  4. Deduplicate the input collection before bulk insertion.

Example fix

// before
tree.Add(key, value); // throws if key exists
// after
if (!tree.Contains(key))
{
    tree.Add(key, value);
}
Defensive patterns

Strategy: validation

Validate before calling

if (!tree.Contains(key))
{
    tree.Add(key, value);
}

Try / catch

try
{
    tree.Add(key, value);
}
catch (ArgumentException)
{
    // duplicate key: update or skip
}

Prevention

When it happens

Trigger: Calling Add with a key that already exists in the tree — detected in Add's private node-walk when the comparer comparison equals 0 at some node.

Common situations: Loading a dataset with duplicate IDs/keys, re-adding a key after a failed bulk load, missing Contains check before Add, or case/format variants that the comparer treats as equal (e.g. a custom comparer normalizing case).

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/547fcd47dfe9b80a. Report an issue: GitHub.

Appendix: source

Thrown at DataStructures/RedBlackTree/RedBlackTree.cs:339

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

        return newNode;
    }

    /// <summary>
    ///     Perform case 2 of insertion by pushing blackness down from parent.
    /// </summary>
    /// <param name="node">Parent of inserted node.</param>
    /// <returns>Grandparent of inserted node.</returns>
    private RedBlackTreeNode<TKey>? AddCase2(RedBlackTreeNode<TKey> node)
    {
        var grandparent = node.Parent;
        var parentDir = comparer.Compare(node.Key, node.Parent!.Key);
        var uncle = parentDir < 0 ? grandparent!.Right : grandparent!.Left;

        node.Color = NodeColor.Black;

View on GitHub (pinned to 96e2905cab)