from anytree import LevelOrderGroupIter from anytree.importer import JsonImporter from sys import argv if len(argv) < 2: print(f"usage: {argv[0]} ") exit() with open(argv[1], 'r') as f: root = JsonImporter().read(f) rows = [] leaves = [] for i in range(len(root.leaves)): rows.append([]) leaves.append({"name":"wrong"}) cur_row = 0 for level in LevelOrderGroupIter(root): cur_row = 0 for node in sorted(level, key=lambda x: x.size, reverse=True): leaf_count = len(node.leaves) if False: #node in root.leaves: leaves[cur_row] = node else: rows[cur_row].append(f'{node.name}') cur_row += max(leaf_count, 1) last_depth = node.depth print(leaves) for i, leaf in enumerate(leaves): #rows[i].append(f"{leaf.name}") rows[i].reverse() print("") for cell in rows[i]: print(f" {cell}") print("") output_rows = [] rows = [] for i in range(len(root.leaves)): output_rows.append([]) def depth_first_search(node, rows, leaf_count): for child in sorted(node.children, key=lambda x: x.size, reverse=True): leaf_count = depth_first_search(child, rows, leaf_count) if node.is_leaf: cur_row = leaf_count rows[cur_row].append(f'{node.name}') leaf_count += 1 else: cur_row = leaf_count - len(node.leaves) rows[cur_row].append(f'{node.name}') return leaf_count depth_first_search(root, output_rows, 0) for row in output_rows: print("") for cell in row: print(f" {cell}") print("")