{"record":{"id":"547fcd47dfe9b80a","repo":"TheAlgorithms/C-Sharp","slug":"key-key-already-exists-in-tree-redblacktree","errorCode":null,"errorMessage":"Key \"{key}\" already exists in tree!","messagePattern":"Key \"(.+?)\" already exists in tree!","errorType":"exception","errorClass":"ArgumentException","httpStatus":null,"severity":"error","filePath":"DataStructures/RedBlackTree/RedBlackTree.cs","lineNumber":339,"sourceCode":"                    node = node.Left;\n                }\n            }\n            else if (compareResult > 0)\n            {\n                if (node.Right is null)\n                {\n                    newNode = new RedBlackTreeNode<TKey>(key, node);\n                    node.Right = newNode;\n                    break;\n                }\n                else\n                {\n                    node = node.Right;\n                }\n            }\n            else\n            {\n                throw new ArgumentException($\"\"\"Key \"{key}\" already exists in tree!\"\"\");\n            }\n        }\n\n        return newNode;\n    }\n\n    /// <summary>\n    ///     Perform case 2 of insertion by pushing blackness down from parent.\n    /// </summary>\n    /// <param name=\"node\">Parent of inserted node.</param>\n    /// <returns>Grandparent of inserted node.</returns>\n    private RedBlackTreeNode<TKey>? AddCase2(RedBlackTreeNode<TKey> node)\n    {\n        var grandparent = node.Parent;\n        var parentDir = comparer.Compare(node.Key, node.Parent!.Key);\n        var uncle = parentDir < 0 ? grandparent!.Right : grandparent!.Left;\n\n        node.Color = NodeColor.Black;","sourceCodeStart":321,"sourceCodeEnd":357,"githubUrl":"https://github.com/TheAlgorithms/C-Sharp/blob/96e2905cab7bc6b33ac0a34ee5bb82ddccbcbb6c/DataStructures/RedBlackTree/RedBlackTree.cs#L321-L357","documentation":"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.","triggerScenarios":"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.","commonSituations":"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).","solutions":["Check tree.Contains(key) before calling Add.","Handle duplicates explicitly: skip or update the value instead of inserting.","Catch ArgumentException around Add when duplicates are expected in the input.","Deduplicate the input collection before bulk insertion."],"exampleFix":"// before\ntree.Add(key, value); // throws if key exists\n// after\nif (!tree.Contains(key))\n{\n    tree.Add(key, value);\n}","handlingStrategy":"validation","validationCode":"if (!tree.Contains(key))\n{\n    tree.Add(key, value);\n}","typeGuard":null,"tryCatchPattern":"try\n{\n    tree.Add(key, value);\n}\ncatch (ArgumentException)\n{\n    // duplicate key: update or skip\n}","preventionTips":["Always Contains-check before Add when duplicates are possible.","Deduplicate bulk input before insertion.","Catch ArgumentException in import paths and decide update-vs-skip.","Mind comparer normalization (case, format) that can make distinct inputs equal."],"tags":["data-structures","red-black-tree","duplicate-key","csharp"],"backgroundTag":"file-already-exists","analyzedSha":"96e2905cab7bc6b33ac0a34ee5bb82ddccbcbb6c","analyzedAt":"2026-09-13T17:04:01.438Z","contentChangedAt":"2026-09-13T17:04:01.438Z","schemaVersion":2},"datasetVersion":"2026-09-16T04:17:20.429Z"}