我想在 python 中構建一個函式,它獲取一些非二叉樹并將樹中的值從左到右按順序放在串列中。例如在這棵樹中 -
C1
/ \
C2 C3
/ | \
C4 C5 C6
我會得到: [ C4 , C5 , C2 , C6 , C1, C3 ] 我看到了這個函式在二叉樹上的作業原理,我試著把它寫成類似的:
def iters(self, by_order):
children = get_children(self) # get_children is a function which give me a list with all the children of a value in the tree
if (len(children) % 2) == 0:
mid = int(len(children) / 2)
else:
mid = int(len(children) / 2) 1
first_half = children[:mid]
second_half = children[mid:]
if len(first_half) != 0:
first_half[0].iters(by_order)
by_order.append(self)
if len(second_half) != 0:
second_half[0].iters(by_order)
return by_order
但我不知道我串列中的所有變數如何讓它變得更好?或者也許是另一種解決方法?我在網上找到了關于二叉樹的資訊,非常感謝!
uj5u.com熱心網友回復:
您的代碼不包括所有子節點,因為您專門從您的first_half和second_half串列中挑選出一個節點以遞回并忽略其他所有內容。可能您想回圈遍歷這些串列中的每一個:
mid = int(len(children) / 2) 1
first_half = children[:mid]
second_half = children[mid:]
for child in first_half:
child.iters(by_order)
by_order.append(self)
for child in second_half
child.iters(by_order)
值得注意的是,這個順序似乎有點尷尬。您選擇將父節點固定在其子節點的正中間(或盡可能靠近,對于奇數個子節點),但這有點隨意。雖然子節點有明確的順序,但不一定有明確的理由按與它們的任何特定關系對父節點進行排序。實際上,對于某些型別的非二叉樹(如 B 樹),樹的每個節點中存盤有多個值,并且適當的中序遍歷會將它們交錯在子節點的值之間。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/486348.html
上一篇:彈跳球碰撞-SFML
