Here is the pseudocode:
for v = 1 to n:
up[v][0] = parent[v]
for j = 1 to log(n):
for v = 1 to n:
up[v][j] = up[up[v][j-1]][j-1]
If up[v][j-1] is null or root, handle it (either set up[v][j] = root or leave it null).
##### ###### ##### ### # # ### # # ###### ## ## ## ## ## ## ## # # # # # ## ##### #### ##### # # # # # # # #### ## # ## ## ## ## # # # # # ## ## # ###### ## ### # ### # ######
##### ###### ##### ### # # ### # # ###### ## ## ## ## ## ## ## # # # # # ## ##### #### ##### # # # # # # # #### ## # ## ## ## ## # # # # # ## ## # ###### ## ### # ### # ######
(Pseudocode for preprocessing)
Here is the pseudocode:
for v = 1 to n:
up[v][0] = parent[v]
for j = 1 to log(n):
for v = 1 to n:
up[v][j] = up[up[v][j-1]][j-1]
If up[v][j-1] is null or root, handle it (either set up[v][j] = root or leave it null).