Graph Theory37 sections · 1633 units
Open in Course

CSES 1674 Subordinates - Algorithm

Single DFS pass

Run DFS from root (node 11). For each node, visit children first, then compute subtree size.

function dfs(u, parent)
    size[u] := 1
    for each child v of u
        if v != parent then
            dfs(v, u)
            size[u] := size[u] + size[v]

After DFS, subordinates[u] = size[u] - 1 (subtract the node itself). This runs in O(n)O(n) time, visiting each node once. The subtree size is a building block for many tree DP problems.

Space complexity is O(n)O(n) for the data structures used.