I may be out of line here or miss the point completely, but I will risk asserting that I think it will be easier if you put each branch completely in brackets. those. write each branch as distinctive [root, [branch1], [branch2], ...]
nestedList1 = ['root', ['aa', ['aa1', ['aa3']], ['aa2']], ['bb', ['bb1']]] nestedList2 = ['root', ['aa', ['aa1', ['aa3']], ['aa2']], ['bb', ['bb1', ['bb2', ['bb4']], ['bb3']]], ['cc', ['cc1']]]
Then you can just recursively reorder so that each branch leaves - 1st, trunk-2nd.
def recursivereverese(l): if len(l)<=1 or type(l) is not list: return l else: new = [] for k in l[::-1]: new.append(recursivereverese(k)) return new
Results of modified nested lists:
In [127]: recursivereverese(nestedList1) Out[127]: [[['bb1'], 'bb'], [['aa2'], [['aa3'], 'aa1'], 'aa'], 'root'] In [128]: recursivereverese(nestedList2) Out[128]: [[['cc1'], 'cc'], [[['bb3'], [['bb4'], 'bb2'], 'bb1'], 'bb'], [['aa2'], [['aa3'], 'aa1'], 'aa'], 'root']
Is that what you were after?
Finding which branch is deeper for a good build is another topic.