You are right - there is no way to do this in a single SOQL query. Please note that your second, desired request will not give you the correct results (it will return only a record if the child account of the nearest parent did not have a parent).
Itβs best to do what you said in your first block of code. You can cross relationships up to 5 objects in depth, so you can include parent.parent.parent.parent.parent.id in your SOQL choice. Iterating over fields - if none of them is null, then it issues a second SOQL query that changes CHILD_ID to parent.parent.parent.parent.parent.id. Thus, you are guaranteed to be able to find a parent without a parent (since salesforce does not guarantee any cycles).
You could make it more elegant by only ever selecting parent.id in the request and making more individual requests, but this will lead you to the API / Governor limitations, so this is probably not a great idea.
If you could use a custom object instead of an account, you could do something like a second request, since you could move from a parent-child relationship to this custom object to yourself, but I'm still not sure There is one request that will give you what you want.
source share