白板的微信
#!/usr/bin/python# coding: utf-8def build_graph(nodes=[]): graph = {} for node in nodes: if not node['prev_node']: # root node if 'root' not in graph: graph['root'] = [] graph['root'].append(node['next_node']) else: if node['prev_node'] not in graph: graph[node['prev_node']] = [] if node['next_node']: graph[node['prev_node']].append(node['next_node']) return graphdef travel(node, graph={}): # print(node) if not graph[node]: return 1, [node] # branch, node max_nodes = [] max_branches = 0 for i in graph[node]: branches, nodes = travel(i, graph) if len(nodes) > len(max_nodes): max_nodes = nodes max_branches += branches max_nodes.append(node) return max_branches, max_nodesif __name__ == '__main__': nodes = [ {"prev_node": "0000000000000005","next_node": "0000000000000006"}, {"prev_node": "0000000000000006","next_node": "0000000000000007"}, {"prev_node": "0000000000000006","next_node": "0000000000000008"}, {"prev_node": "0000000000000008","next_node": "0000000000000012"}, {"prev_node": "0000000000000009","next_node": "0000000000000010"}, {"prev_node": "0000000000000010","next_node": "0000000000000011"}, {"prev_node": "0000000000000014","next_node": "0000000000000015"}, {"prev_node": "0000000000000015","next_node": "0000000000000016"}, {"prev_node": "0000000000000016","next_node": "0000000000000017"}, {"prev_node": "0000000000000018","next_node": "0000000000000019"}, {"prev_node": "0000000000000020","next_node": "0000000000000021"}, {"prev_node": "0000000000000019","next_node": "0000000000000020"}, {"prev_node": "0000000000000012","next_node": "0000000000000022"}, {"prev_node": "0000000000000022","next_node": "0000000000000023"}, {"prev_node": "0000000000000023","next_node": "0000000000000009"}, {"prev_node": "0000000000000011","next_node": "0000000000000024"}, {"prev_node": "0000000000000024","next_node": "0000000000000014"}, {"prev_node": "0000000000000017","next_node": "0000000000000025"}, {"prev_node": "0000000000000025","next_node": "0000000000000018"}, {"prev_node": "0000000000000007","next_node": "0000000000000021"}, {"prev_node": None, "next_node": "0000000000000005"}, {"prev_node": "0000000000000021", "next_node": None} ] graph = build_graph(nodes) branches, nodes = travel('root', graph) print("branch num: %d" % branches) print("max depth branch:") for i in nodes[::-1]: print(i)branch num: 2max depth branch:root0000000000000005000000000000000600000000000000080000000000000012000000000000002200000000000000230000000000000009000000000000001000000000000000110000000000000024000000000000001400000000000000150000000000000016000000000000001700000000000000250000000000000018000000000000001900000000000000200000000000000021