0
我在正確處理樹時遇到了問題。樹很簡單,只是一個節點和兒童Python:樹遞歸問題
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
。每個NIL
表示1(子)樹正在結束。
我目前的版本只輸出以下內容:1 2 5 NIL 3 4 NIL
,沒有多個NIL
s。任何想法我離開了?
def linearize(self):
print self.node,
if self.children == []:
print "NIL",
for child in self.children:
child.linearize()
一般來說,使用'children = []'作爲默認是一個壞主意......請參閱http://stackoverflow.com/questions/1132941/least-astonishment-in-python-the-mutable-default-論點 – mgilson
正式注意。這只是提供 –