{"record":{"id":"61695fc0725a9fc8","repo":"TheAlgorithms/C-Sharp","slug":"key-key-already-exists-in-tree","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/BinarySearchTree/BinarySearchTree.cs","lineNumber":191,"sourceCode":"            }\n        }\n        else if (compareResult < 0)\n        {\n            if (node.Right is not null)\n            {\n                Add(node.Right, key);\n            }\n            else\n            {\n                var newNode = new BinarySearchTreeNode<TKey>(key);\n                node.Right = newNode;\n            }\n        }\n\n        // Key is already in tree.\n        else\n        {\n            throw new ArgumentException($\"\"\"Key \"{key}\" already exists in tree!\"\"\");\n        }\n    }\n\n    /// <summary>\n    ///     Removes a node with the specified key from the BST.\n    /// </summary>\n    /// <param name=\"parent\">The parent node of <paramref name=\"node\" />.</param>\n    /// <param name=\"node\">The node to check/search from.</param>\n    /// <param name=\"key\">The key to remove.</param>\n    /// <returns>true if the operation was successful, false otherwise.</returns>\n    /// <remarks>\n    ///     Removing a node from the BST can be split into three cases:\n    ///     <br></br>\n    ///     0. The node to be removed has no children. In this case, the node can just be removed from the tree.\n    ///     <br></br>\n    ///     1. The node to be removed has one child. In this case, the node's child is moved to the node's parent,\n    ///     then the node is removed from the tree.\n    ///     <br></br>","sourceCodeStart":173,"sourceCodeEnd":209,"githubUrl":"https://github.com/TheAlgorithms/C-Sharp/blob/96e2905cab7bc6b33ac0a34ee5bb82ddccbcbb6c/DataStructures/BinarySearchTree/BinarySearchTree.cs#L173-L209","documentation":"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.","triggerScenarios":"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).","commonSituations":"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.","solutions":["Check Contains(key) before Add and skip or update the existing node","Deduplicate input before inserting (Distinct on keys)","Catch ArgumentException with Message.Contains(\"already exists\") when duplicates are expected","If overwrite semantics are needed, write an Update method or use Dictionary instead"],"exampleFix":"// before\nbst.Add(key, value); // throws on duplicate\n// after\nif (!bst.Contains(key))\n{\n    bst.Add(key, value);\n}\nelse\n{\n    bst.Update(key, value); // or skip\n}","handlingStrategy":"validation","validationCode":"if (!bst.Contains(key)) bst.Add(key, value);","typeGuard":"null","tryCatchPattern":"try { bst.Add(key, value); } catch (ArgumentException ex) when (ex.Message.Contains(\"already exists\")) { /* duplicate handling */ }","preventionTips":["Check Contains before Add","Deduplicate input collections before insertion","Use a Dictionary if overwrite semantics are required"],"tags":["csharp","bst","duplicate-key"],"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"}