#coding:utf-8 __author__ = 'lv' tree = ["a",["b",["d",[],[]],["e",[],[]]],["c",["f",[],[]],["g",[],[]]]] #查找二叉树中路径最远的节点和最长路径。 vertex_len = {} def dfs(tree,length): vertex_len[tree[0]] = length length += 1 if len(tree[1])==0 and len(tree[2])==0: return for child in tree: if isinstance(child,list): dfs(child,length) dfs(tree,0) max_len = 0 ver_max_len = 0 for val in vertex_len.itervalues(): ver_max_len = val if val > ver_max_len else ver_max_len ver_max = [] for key in vertex_len.iterkeys(): if vertex_len[key] == ver_max_len: ver_max.append(key) print ver_max_len print ver_max
用嵌套列表表示的二叉树的相关操作
最新推荐文章于 2022-07-22 12:01:12 发布