参考楼主的写了一个递归的
class TreeNode(object):
def __init__(self,val,parent):
self.val = val
self.child = []
self.parent = parent
def SetPre(pre,s):
pre=pre.replace('-'," ")
pre=pre.replace('`'," ")
return pre+s
def PrintTree(root,pree):
if root.parent == -1:
print(root.val)
else:
print(pree+" "+root.val)
if root.child:
root.child.sort(key = lambda x:x.val)
for ind,child in enumerate(root.child):
if ind != len(root.child)-1:
pre = SetPre(pree,"|--")
PrintTree(child,pre)
else:
pre = SetPre(pree,"`--")
PrintTree(child,pre)
n = int(raw_input())
nodes = []
for i in xrange(n):
fileParent = raw_input().split()
node = TreeNode(fileParent[0],int(fileParent[1]))
nodes.append(node)
if int(fileParent[1]) != -1:
nodes[int(fileParent[1])].child.append(node)
PrintTree(nodes[0],"")