[英]With 2 list of strings, trying to find a way to print the string in the same position/order from the opposite list.(Python)
[英]Trouble trying to print string in order from a tree
我想將一個樹變成一個字符串並獲得預處理順序(從root開始,然后向下移動所有左邊的節點然后向右移動到右邊的節點)示例:tree(root(left(a)(b))(right(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 cd"
。 我懷疑這是因為在將value.children[0]
設置為value時,它不會for i in value.children
運行for i in value.children
但我不知道為什么。 這里有什么問題?
代碼的問題是,您在for循環中設置了value = i
。 當你這樣做時,你希望你的代碼回到while ...:
而不是while ...:
但它會轉到for循環的下一次迭代。 結果是在實際繼續該值之前,將值設置為for循環中節點的最后一個子節點 。 這會跳過除每個節點的最后一個子節點之外的所有子節點,這就是您看到自己所處行為的原因。 為了在正確的情況下盡可能接近原始解決方案,我建議使用遞歸代替此代碼,因為在這種情況下更容易推理:
def prestr_helper(value):
if len(value.children) > 0:
return value.data + ' ' + \
' '.join(prestr_helper(child) for child in value.children)
else:
return value.data
def prestr(self):
print(prestr_helper(self.root))
但是,這確實存在Python遞歸限制的問題,因此在深度為1000或更多(近似)的樹中會失敗。 為了避免這種限制,您必須實現迭代解決方案,例如此處描述的解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.