Get structure top ancestor
getAncestors() gets all entries that are ancestors. Since you're looping through them what rootEntry is set to last time through is the closest ancestor.

You can avoid the loop and just get the first one:

{% set rootEntry = entry.getAncestors().first() %}