Using your favorite automation tool, this will get you all of your branches and descendants:
https://YOURDOMAIN/manage/v1/orgchart?search_type=1&flattened=true
For each branch ID returned, you would want to retrieve the number of users:
https://YOURDOMAIN/manage/v1/orgchart/BRANCHNUMBER/users?page_size=1
The “page_size=1” parameter will return a single user (in order to limit the amount of data returned). The only part of the return you’re interested in is under the JSON path data.total_count
This will provide you with the number of users for that branch including subbranches. You’re looking for that number to be zero. At that point you could use the Batch deletion of branches endpoint to remove them this way:
https://YOURDOMAIN/manage/v1/orgchart/batch
{
"items": [
{
"id": BRANCHNUMBER
}
]
}