TheAlgorithms/Java · error · IllegalArgumentException

Invalid node: {}

Error message

Invalid node: {}

What it means

Thrown by CentroidTree.getParent(int node) when the node index is outside the valid range [0, n). getParent indexes the internal parent[] array, so an out-of-range index would cause ArrayIndexOutOfBoundsException. The IllegalArgumentException rejects invalid node identifiers with their offending value.

Source

Thrown at src/main/java/com/thealgorithms/datastructures/trees/CentroidDecomposition.java:131

         */
        private int findCentroid(int u, int p, int totalSize) {
            for (int v : adj.get(u)) {
                if (v != p && !removed[v] && subtreeSize[v] > totalSize / 2) {
                    return findCentroid(v, u, totalSize);
                }
            }
            return u;
        }

        /**
         * Gets the parent of a node in the centroid tree.
         *
         * @param node the node
         * @return parent node in centroid tree, or -1 if root
         */
        public int getParent(int node) {
            if (node < 0 || node >= n) {
                throw new IllegalArgumentException("Invalid node: " + node);
            }
            return parent[node];
        }

        /**
         * Gets the root of the centroid tree.
         *
         * @return root node
         */
        public int getRoot() {
            return root;
        }

        /**
         * Gets the number of nodes in the tree.
         *
         * @return number of nodes
         */

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Ensure node ids are in [0, n-1]; convert 1-based external ids by subtracting 1.
  2. Filter out sentinel values (e.g., -1 from getParent itself) before passing them back in.
  3. Validate node range at the boundary where external data enters your code.
  4. Iterate with i < n rather than i <= n.

Example fix

// before
int p = ct.getParent(nodeId);
// after
if (nodeId < 0 || nodeId >= n) {
    throw new IllegalArgumentException("bad node id: " + nodeId);
}
int p = ct.getParent(nodeId);
Defensive patterns

Strategy: validation

Validate before calling

if (node >= 0 && node < n) {
    int parent = ct.getParent(node);
}

Prevention

When it happens

Trigger: Passing a node id derived from 1-indexed external data into a 0-indexed tree. Passing n (the count) as a node id. Passing a negative value from a sentinel or uninitialized variable.

Common situations: Mixing 0-based and 1-based indexing between input parsing and the algorithm. Off-by-one when iterating node ids (e.g., i <= n instead of i < n). Using a node id returned as -1 (no-parent sentinel) without filtering.

Related errors


AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13). Data as JSON: /api/errors/e66d515ff512044c. Report an issue: GitHub.