I mean, the code DOES work if pages is sorted in ascending order and children ALWAYS have higher pks than parents, but these assumptions might not always be true.