{"record":{"id":"315fdda594576a2f","repo":"TheAlgorithms/Java","slug":"tree-must-have-exactly-n-1-edges","errorCode":null,"errorMessage":"Tree must have exactly n-1 edges","messagePattern":"Tree must have exactly n-1 edges","errorType":"exception","errorClass":"IllegalArgumentException","httpStatus":null,"severity":"error","filePath":"src/main/java/com/thealgorithms/datastructures/trees/CentroidDecomposition.java","lineNumber":192,"sourceCode":"    }\n\n    /**\n     * Creates a centroid tree from an edge list.\n     *\n     * @param n number of nodes (0-indexed: 0 to n-1)\n     * @param edges list of edges where each edge is [u, v]\n     * @return CentroidTree object\n     * @throws IllegalArgumentException if n &lt;= 0 or edges is invalid\n     */\n    public static CentroidTree buildFromEdges(int n, int[][] edges) {\n        if (n <= 0) {\n            throw new IllegalArgumentException(\"Number of nodes must be positive\");\n        }\n        if (edges == null) {\n            throw new IllegalArgumentException(\"Edges cannot be null\");\n        }\n        if (edges.length != n - 1) {\n            throw new IllegalArgumentException(\"Tree must have exactly n-1 edges\");\n        }\n\n        List<List<Integer>> adj = new ArrayList<>();\n        for (int i = 0; i < n; i++) {\n            adj.add(new ArrayList<>());\n        }\n\n        for (int[] edge : edges) {\n            if (edge.length != 2) {\n                throw new IllegalArgumentException(\"Each edge must have exactly 2 nodes\");\n            }\n            int u = edge[0];\n            int v = edge[1];\n\n            if (u < 0 || u >= n || v < 0 || v >= n) {\n                throw new IllegalArgumentException(\"Invalid node in edge: [\" + u + \", \" + v + \"]\");\n            }\n","sourceCodeStart":174,"sourceCodeEnd":210,"githubUrl":"https://github.com/TheAlgorithms/Java/blob/fdfb9a395b310167a66bd29e311e36e0e3e9b964/src/main/java/com/thealgorithms/datastructures/trees/CentroidDecomposition.java#L174-L210","documentation":"Thrown by CentroidDecomposition.buildFromEdges when the number of edges is not exactly n-1. A valid tree on n nodes has precisely n-1 edges; any other count indicates a malformed tree (cycle, disconnected, or extra edges). The IllegalArgumentException enforces this invariant before constructing the adjacency list.","triggerScenarios":"Passing n-2 edges (disconnected forest). Passing n edges (a cycle). Passing edges with duplicates or self-loops inflating the count. Mismatch between n and the actual vertex set used to build edges.","commonSituations":"Input data that is not actually a tree (general graph mistaken for a tree). Off-by-one in computing n relative to the edges. Merging edge lists that introduce duplicates. Self-loops or duplicate undirected edges counted twice.","solutions":["Verify the input is a valid tree: exactly n-1 unique edges connecting all n nodes with no cycles.","Ensure n matches the true vertex count of the edge list.","Deduplicate undirected edges (treat [u,v] and [v,u] as one) before counting.","Run a connectivity/cycle check before calling buildFromEdges."],"exampleFix":"// before\nCentroidTree ct = CentroidDecomposition.buildFromEdges(n, edges);\n// after\nif (edges.length != n - 1) {\n    throw new IllegalArgumentException(\n        \"Expected \" + (n - 1) + \" edges for \" + n + \" nodes, got \" + edges.length);\n}\nCentroidTree ct = CentroidDecomposition.buildFromEdges(n, edges);","handlingStrategy":"validation","validationCode":"if (edges.length == n - 1) {\n    CentroidTree ct = CentroidDecomposition.buildFromEdges(n, edges);\n} else {\n    throw new IllegalArgumentException(\"tree must have n-1 edges\");\n}","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Verify the input is a valid tree (n-1 edges, connected, acyclic).","Deduplicate undirected edges before counting.","Keep n consistent with the edge set's vertex range."],"tags":["tree","invalid-argument","java","datastructures","centroid-decomposition","graph-invariant"],"backgroundTag":null,"analyzedSha":"fdfb9a395b310167a66bd29e311e36e0e3e9b964","analyzedAt":"2026-08-13T23:36:13.315Z","schemaVersion":2},"datasetVersion":"2026-08-14T05:17:29.042Z"}