Moved logic for handling terminal nodes into recursive function