[英]How to search binary tree nodes to get longest tree in python using ADT
T = [[[[], [3, []]], [5, [[[[], [6, []]], [2, [[], [1, []]]]], [4, [[], [3, [[], [7, []]]]]]]]], [2, [[], [8, []]]]]
是二叉樹的表示。
上面的T
代碼很長,滾動瀏覽完整代碼
我正在尋找最長的樹,其節點總和是給定數字的倍數。
示例給出7
上面的樹T
作為searchMax(T, 7)
, [[2,5], [4,3], [7]]
返回,因為它是最長的,並且其總和是 7 的倍數
我已經定義了以下代碼
def cons(x, y):
return [x, y]
def car(p):
return p[0]
def cdr(p):
return p[1]
nil = []
def makeBinTree(root, left, right):
return cons(left, cons(root, right))
emptyTree = nil
def isEmpty(tree):
if len(tree) < 1:
return True
else:
return False
def root(tree):
return tree[1][0]
def left(tree):
return tree[0][1]
def right(tree):
return [1][1]
def searchMax(tree, number):
但我只是不知道從那里去哪里。 你能幫我解決這個問題嗎?
我會編寫一個函數來遍歷樹中所有可能的路徑。 然后我將遍歷這些路徑,並選擇加起來為 7 倍數的路徑,然后從這些路徑中選擇最長的路徑。
def isEmpty(tree):
if len(tree) < 1:
return True
else:
return False
def root(tree):
return tree[1][0]
def left(tree):
return tree[0]
def right(tree):
return tree[1][1]
def iter_all_paths(t):
if isEmpty(t):
return
yield [root(t)]
for child in (left(t), right(t)):
for path in iter_all_paths(child):
yield [root(t)] + path
def searchMax(t, x):
#find all paths that add up to a multiple of x
candidates = []
for path in iter_all_paths(t):
if sum(path) % x == 0:
candidates.append(path)
if not candidates:
return None
return max(candidates, key=len)
T = [[[[], [3, []]], [5, [[[[], [6, []]], [2, [[], [1, []]]]], [4, [[], [3, [[], [7, []]]]]]]]], [2, [[], [8, []]]]]
print(searchMax(T, 7))
結果:
[2, 5, 4, 2, 1]
這與您的預期結果 [2, 5, 4, 3, 7] 不同。 這兩個解決方案具有相同的長度,所以我認為返回一個或另一個沒問題。 如果長度有關系,我的解決方案將返回最左邊的路徑。
也許您在想“實際上我不想要最長的路徑長度,而是想要最大的節點總和”。 然后 [2, 5, 4, 3, 7] 會以 7 分擊敗 [2, 5, 4, 2, 1]。 如果這是您想要的,您可以更改searchMax
的最后一行以return max(candidates, key=sum)
。
您可能還會想“我希望結果是一個列表列表,而不是一個整數列表。我希望每個子列表加起來都是數字的倍數。而不是[2, 5, 4, 3, 7]
,我想要[[2, 5], [4, 3], [7]]
。
您可以編寫一個函數,將列表searchMax
多個相加的塊,並在從searchMax
返回之前調用該函數。
def chunk(seq, x):
result = [[]]
for item in seq:
result[-1].append(item)
if sum(result[-1]) % x == 0:
result.append([])
if not result[-1]:
del result[-1]
return result
#later, in searchMax...
return chunk(max(candidates, key=len), x)
結果:
[[2, 5], [4, 2, 1]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.