First, root the tree at node . Run DFS to compute size[v] for each node, counting how many nodes are in each subtree. For each node, the heavy child is the child with the largest subtree. Mark the edge to the heavy child as heavy, all others as light.
Run HLD to assign each node to a chain and compute pos[v] within its chain. Also compute head[v] for each node to identify chain boundaries.