{"record":{"id":"16cdedef56dd8eef","repo":"TheAlgorithms/C-Sharp","slug":"key-key-is-not-in-the-avl-tree","errorCode":null,"errorMessage":"Key \"{key}\" is not in the AVL tree.","messagePattern":"Key \"(.+?)\" is not in the AVL tree\\.","errorType":"exception","errorClass":"KeyNotFoundException","httpStatus":null,"severity":"error","filePath":"DataStructures/AVLTree/AVLTree.cs","lineNumber":380,"sourceCode":"\n        // Check all of the new node's ancestors for imbalance and perform\n        // necessary rotations\n        node.UpdateBalanceFactor();\n\n        return Rebalance(node);\n    }\n\n    /// <summary>\n    ///     Recursive function to remove node from tree.\n    /// </summary>\n    /// <param name=\"node\">Node to check for key.</param>\n    /// <param name=\"key\">Key value to remove.</param>\n    /// <returns>New node with key removed.</returns>\n    private AvlTreeNode<TKey>? Remove(AvlTreeNode<TKey>? node, TKey key)\n    {\n        if (node == null)\n        {\n            throw new KeyNotFoundException(\n                $\"\"\"Key \"{key}\" is not in the AVL tree.\"\"\");\n        }\n\n        // Normal binary search tree removal\n        var compareResult = comparer.Compare(key, node.Key);\n        if (compareResult < 0)\n        {\n            node.Left = Remove(node.Left, key);\n        }\n        else if (compareResult > 0)\n        {\n            node.Right = Remove(node.Right, key);\n        }\n        else\n        {\n            if (node.Left is null && node.Right is null)\n            {\n                return null;","sourceCodeStart":362,"sourceCodeEnd":398,"githubUrl":"https://github.com/TheAlgorithms/C-Sharp/blob/96e2905cab7bc6b33ac0a34ee5bb82ddccbcbb6c/DataStructures/AVLTree/AVLTree.cs#L362-L398","documentation":"This KeyNotFoundException is thrown by the AVL tree's recursive Remove when the search descends past a null child, meaning the requested key does not exist in the tree. The library treats removal of an absent key as a programming error rather than a silent no-op, so it fails fast with the missing key in the message. Callers must ensure the key exists (e.g. via ContainsKey) or catch this exception.","triggerScenarios":"Calling AVLTree.Remove(key) (or the public Remove overload that delegates to the private Remove(node, key) at DataStructures/AVLTree/AVLTree.cs:380) with a key that was never inserted, or with a key that was already removed. Also occurs when a custom comparer orders keys differently from the one used at insertion time, so the search path misses the stored key.","commonSituations":"Removing an item twice in cleanup logic; deleting a key built from user input that never existed; switching or misconfiguring a custom comparer so lookups and insertions disagree; assuming Remove returned a success/failure indicator when it actually throws.","solutions":["Check that the key exists before removing: call ContainsKey/Contains and only call Remove when it returns true.","Wrap the Remove call in try/catch (KeyNotFoundException) if absence is an expected, non-fatal condition.","Verify the same comparer (default vs custom) is used for every Insert/Remove/Search operation on the tree.","Log or validate the key source (user input, upstream data) to avoid deleting keys that were never added."],"exampleFix":"// before\navlTree.Remove(userKey); // throws if userKey was never inserted\n\n// after\nif (avlTree.ContainsKey(userKey))\n{\n    avlTree.Remove(userKey);\n}\nelse\n{\n    // handle absent key: log, return false, etc.\n}","handlingStrategy":"try-catch","validationCode":"// C#\nif (!avlTree.ContainsKey(key))\n{\n    // skip removal or log; key is absent\n}\nelse\n{\n    avlTree.Remove(key);\n}","typeGuard":"// C#\nstatic bool KeyExists<TK>(AVLTree<TK> tree, TK key) =>\n    tree is not null && tree.ContainsKey(key);","tryCatchPattern":"// C#\ntry\n{\n    avlTree.Remove(key);\n}\ncatch (KeyNotFoundException ex)\n{\n    // key absent — log ex.Message and continue\n}","preventionTips":["Always gate Remove with ContainsKey when absence is possible.","Use the same comparer instance for insert and remove operations.","In drain loops, iterate while the tree reports non-empty rather than a fixed key count.","Treat Remove as throwing, not boolean-returning; never ignore the possibility of absence."],"tags":["keynotfound","avl-tree","remove","data-structures"],"backgroundTag":"record-not-found","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"}