在python中打印树中的根目录和子目录
我有一个程序,通过嵌套对象创建来创建一棵树,如下所示。我知道这不是正确的方法,但我必须打印每个级别的值在python中打印树中的根目录和子目录,python,object,Python,Object,我有一个程序,通过嵌套对象创建来创建一棵树,如下所示。我知道这不是正确的方法,但我必须打印每个级别的值 class Node(object): def __init__(self, value, children): self.value = value self.children = children exTree = Node(1, [ Node(2, []), Node(3, [
class Node(object):
def __init__(self, value, children):
self.value = value
self.children = children
exTree = Node(1, [
Node(2, []), Node(3, [
Node(4, [
Node(5, []), Node(6, [
Node(7,[])
])])])])
我尝试访问这些值,但找不到方法
树如下-我必须打印以下值:
print(treeToString(extree)
>1
>23
>4
>56
>7
更新-
到目前为止,我能够实现以下目标,但其格式不符合要求。我只需要创建一个函数
def treeToString(exTree):
print(exTree.value)
for child in exTree.children:
treeToString(child)
treeToString(extree)
输出-
1
2
3
4
5
6
7
我用以下方法解决了这个问题:
def treeToString(extree):
rep = str(extree.value) + "\n"
return _treeToStringAux(extree, rep)
def _treeToStringAux(extree, rep):
for child in extree.children:
rep+= str(child.value)
if not (rep[-1] == "\n"):
rep+="\n"
for child in extree.children:
rep = _treeToStringAux(child, rep)
return rep
print(treeToString(exTree))
给出了结果
我检查
\n
的部分是因为由于我遍历树的方式,我有时会得到两条换行线,我会使用生成器一次生成一个级别。这是非常通用的,因为它允许您对输出执行各种操作,而不仅仅是打印
def级别(树):
如果是树:
产量元组([tree.value for tree in trees])
各级产量([child for tree in tree for child in tree.children])
例如:
>>列表(级别([exTree]))
[(1,), (2, 3), (4,), (5, 6), (7,)]
从那里,您可以根据需要打印,或者编写pytest和doctest,或者在其他应用程序中使用
对于v级([exTree]):
打印(“”.join(映射(str,v)))
输出:
1
2 3
4.
5 6
7.
(注意:使用上面的'.join(…)
来抑制空格并精确匹配所需的输出,但我认为这对空格更具解释性)。这称为级别顺序遍历。访问值时遇到了什么问题exTree.value
应该为您提供1
[exTree.children中节点的node.value]
应该为您提供[2,3]
。是吗?@Samwise几分钟前,我还获得了前两个关卡。但不能再深入了。我正在尝试递归地访问这些值。谷歌“水平顺序遍历”,或者“广度优先搜索”。使用迭代循环比使用递归更容易实现广度优先。