Полагаю, это решает проблему:
#!/usr/bin/env python
def f(txt):
stack = []
ret = {}
for line in txt.split('\n'):
a = line.split(' ')
level = len(a) - 1
key = a[-1]
stack = stack[:level]
ret[key] = stack[-1] if len(stack) > 0 else None
stack.append(key)
return ret
print f("""Root
Branch1
LeafA
LeafB
Branch2
LeafC
LeafZ
LeafD""")
print f("""Root1
Branch1
LeafA
LeftZ
Branch2
LeftB
Root2
Branch3""")
Вывод:
{'LeafD': 'Branch2', 'LeafA': 'Branch1', 'Branch2': 'Root', 'LeafC': 'Branch2', 'LeafB': 'Branch1', 'Branch1': 'Root', 'Root': None, 'LeafZ': 'LeafC'}
{'LeafA': 'Branch1', 'Branch2': 'Root1', 'Branch1': 'Root1', 'LeftZ': 'LeafA', 'LeftB': 'Branch2', 'Branch3': 'Root2', 'Root1': None, 'Root2': None}