{"record":{"id":"e2628914c3f42df7","repo":"TheAlgorithms/Python","slug":"node-with-label-label-already-exists","errorCode":null,"errorMessage":"Node with label {label} already exists","messagePattern":"Node with label (.+?) already exists","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"data_structures/binary_tree/binary_search_tree_recursive.py","lineNumber":83,"sourceCode":"        >>> assert t.root.right.parent == t.root\n        >>> assert t.root.right.label == 10\n\n        >>> t.put(3)\n        >>> assert t.root.left.parent == t.root\n        >>> assert t.root.left.label == 3\n        \"\"\"\n        self.root = self._put(self.root, label)\n\n    def _put(self, node: Node | None, label: int, parent: Node | None = None) -> Node:\n        if node is None:\n            node = Node(label, parent)\n        elif label < node.label:\n            node.left = self._put(node.left, label, node)\n        elif label > node.label:\n            node.right = self._put(node.right, label, node)\n        else:\n            msg = f\"Node with label {label} already exists\"\n            raise ValueError(msg)\n\n        return node\n\n    def search(self, label: int) -> Node:\n        \"\"\"\n        Searches a node in the tree\n\n        >>> t = BinarySearchTree()\n        >>> t.put(8)\n        >>> t.put(10)\n        >>> node = t.search(8)\n        >>> assert node.label == 8\n\n        >>> node = t.search(3)\n        Traceback (most recent call last):\n            ...\n        ValueError: Node with label 3 does not exist\n        \"\"\"","sourceCodeStart":65,"sourceCodeEnd":101,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/data_structures/binary_tree/binary_search_tree_recursive.py#L65-L101","documentation":"Raised by BinarySearchTree.put() (via _put) when inserting a label that already exists in the tree. This recursive BST implementation stores unique keys only: the _put recursion compares label against node.label and hits the else branch on equality, raising ValueError. It is a duplicate-key guard, matching the semantics of dict assignment but refusing silent overwrite.","triggerScenarios":"Calling t.put(x) a second time with the same integer x, e.g. t.put(8); t.put(8). Also any bulk-insert loop over data containing repeated values (duplicates in an input list fed to put in a loop).","commonSituations":"Loading a dataset with duplicate values into the tree; re-running initialization code against an already-populated tree; off-by-one loops that re-insert the last element.","solutions":["Deduplicate input before insertion: `for label in dict.fromkeys(labels): t.put(label)`","Check membership first: `if not t.exists(label): t.put(label)` (or guard with a search/try except)","Wrap the put call in try/except ValueError and ignore duplicates if overwrite semantics are acceptable","If duplicates must be stored, switch to a multiset-style structure or store counts in node payloads"],"exampleFix":"# before\nfor v in [8, 10, 8]:\n    t.put(v)  # ValueError on second 8\n\n# after\nfor v in dict.fromkeys([8, 10, 8]):\n    t.put(v)","handlingStrategy":"validation","validationCode":"from data_structures.binary_tree.binary_search_tree_recursive import BinarySearchTree\n\ndef safe_put(t: BinarySearchTree, label: int) -> bool:\n    try:\n        t.search(label)\n        return False  # already present\n    except ValueError:\n        t.put(label)\n        return True","typeGuard":null,"tryCatchPattern":"try:\n    t.put(label)\nexcept ValueError as e:\n    if \"already exists\" not in str(e):\n        raise\n    # treat as no-op duplicate","preventionTips":["Deduplicate inputs with dict.fromkeys before bulk insertion","Treat put as assert-unique: only call it for keys you have not inserted","In tests, build trees from sorted unique fixtures"],"tags":["binary-tree","duplicate-key","validation","insert"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}