我想將一棵樹變成一個字符串並獲取prestr的順序(以root開頭,然後沿着所有左邊的節點向右移動)例如:tree(root(左(a)(b))(右(c)(d)))將是「root left ab right cd」。嘗試從樹中按順序打印字符串時遇到問題
class TreeNode:
def __init__(self, data = None):
self.data = data
self.children = []
class Tree:
def __init__(self, string = None):
self.root = None
def prestr(self):
string1 = ""
value = self.root
string1 += value.data
string1 += " "
while len(value.children) > 0:
for i in value.children:
string1 += i.data
string1 += " "
value = i
print(string1)
這與
tree (root (left (a) (b)) (right (c) (d)))
運行此代碼時,我得到:"root left right c d"
。我懷疑這是因爲它不會在value.children[0]
上運行for i in value.children
,當它被設置爲值但我不知道爲什麼。這裏有什麼問題?