def lines2tree(self, lines): # 寻找根节点 i2p = dict([[p[0], p[6]] for p in lines]) # 根据行数i返回其parent的行数p p2t = dict() # 根据行数p返回其对应的树t global root for i in i2p: if int(i2p[i]) == -1: root = Tree(lines[int(i - 1)]) p2t[i] = root break def add_node(i, line): temp = Tree(line) if int(i2p[i]) not in p2t: # 如果待入树节点的父亲还没有加入树,递归加入 add_node(int(i2p[i]), lines[int(i2p[i])]) p2t[int(i2p[i])].add_child(temp) p2t[i] = temp for i, line in enumerate(lines): # print(i, p2t) if int(i2p[i + 1]) == -1: # 如果是根节点, 跳过 continue if i + 1 not in p2t: # 如果第i行还没有成为树节点 add_node(i + 1, line) # 将它父亲所在的行生成节点并加入树 return root
def lines2tree(lines): # lines[0][5]不一定是-1 # 寻找根节点 i2p = dict([[int(p[0]), int(p[6])] for p in lines]) # 根据行数i返回其parent的行数p p2t = dict() # 根据行数p返回其对应的树t global root for i in i2p: if int(i2p[i]) == -1: root = Tree(lines[int(i - 1)]) p2t[i] = root break def add_node(i, line): temp = Tree(line) if int(i2p[i]) not in p2t: # 如果待入树节点的父亲还没有加入树,递归加入 add_node(int(i2p[i]), lines[int(i2p[i])]) p2t[int(i2p[i])].add_child(temp) p2t[i] = temp for i, line in enumerate(lines): # print(i, p2t) try: if int(i2p[i + 1]) == -1: # 如果是根节点, 跳过 continue except KeyError: print(lines) if i + 1 not in p2t: # 如果第i行还没有成为树节点 add_node(i + 1, line) # 将它父亲所在的行生成节点并加入树 # print(root.depth()) # print(root.size()) # print(lines.shape) # if root.size() != lines.shape[0]: # raise KeyError('') return root
def add_node(i, line): temp = Tree(line) if int(i2p[i]) not in p2t: # 如果待入树节点的父亲还没有加入树,递归加入 add_node(int(i2p[i]), lines[int(i2p[i])]) p2t[int(i2p[i])].add_child(temp) p2t[i] = temp