I don't understand this function. Why does it return `tree` sometimes? Please add comments or rename variables to improve readability.