Python:树递归问题

Python:树递归问题,python,recursion,tree,Python,Recursion,Tree,我在正确处理树时遇到问题。树很简单,只是一个节点和子节点列表 class Tree (object): __slots__ = "node","children" def __init__(self,node,children=[]): self.node = node self.children = children 然而,使用线性化技术,我们应该检测给定分支结束的(子)树数量。例如,如果我们这样构造一棵树: t = Tree(1, [Tree

我在正确处理树时遇到问题。树很简单,只是一个节点和子节点列表

class Tree (object):
    __slots__ = "node","children"
    def __init__(self,node,children=[]):
        self.node = node
        self.children = children
然而,使用线性化技术,我们应该检测给定分支结束的(子)树数量。例如,如果我们这样构造一棵树:

t = Tree(1, [Tree(2, [Tree(5), Tree(3, [Tree(4)])])])
然后
t.linearize()
应输出
1 2 5 NIL 3 4 NIL NIL NIL
。每个
NIL
表示一个正在结束的(子)树

我的当前版本只输出以下内容:
125nil34nil
,没有多个
NIL
s。知道我漏掉了什么吗

def linearize(self):
    print self.node,
    if self.children == []:
        print "NIL",
    for child in self.children:
        child.linearize()
你真的想要:

def linearize(self):
    print self.node,
    for child in self.children:
        child.linearize()
    print "NIL",
其中:

In [5]: t.linearize()
1 2 5 NIL 3 4 NIL NIL NIL NIL
现在,如果有子对象,则不打印“NIL”。(正如评论中所指出的,如果孩子不是其他人[]或其他什么东西,你真的需要
children=None
,然后是
self.children=children。)


您可能还想重新编写它,以产生每个元素,而不仅仅是打印它们,但这显然取决于您。

一般来说,使用
子元素=[]
作为默认值是个坏主意。。。见适当注明。这是刚刚提供的