http://pat.zju.edu.cn/contests/pat-practise/1004
打印多叉树每一级中叶节点的个数,其实就是检查从根节点到每个叶节点的长度,合并相同长度的个数。深度优先遍历一把就好了。唯一要注意的是只有一个根节点的情况,为了递归方便加了一个指向根节点的虚拟节点'00'
1 def CountPath(list, lenth): 2 for item in list: 3 if item in dict.keys(): 4 CountPath(dict[item], lenth + 1) 5 else: 6 if lenth in dictlenth.keys(): 7 dictlenth[lenth] = dictlenth[lenth] + 1 8 else: 9 dictlenth[lenth] = 1 10 11 dictlenth = {} 12 dict = {'00':['01']} 13 node, nl = raw_input().split() 14 for i in range(int(nl)): 15 list = raw_input().split() 16 dict[list[0]] = list[2:] 17 CountPath(dict['00'], 1) 18 for i in range(1, max(dictlenth.keys())+1): 19 if i in dictlenth.keys(): 20 print dictlenth[i], 21 else: 22 print 0,