簡體   English   中英

在遞歸查找最大路徑總和時,附加二叉樹的左或右方向

[英]While recursively finding max path sum, append left or right direction of binary tree

我正在創建python代碼來識別二叉樹的最大(節點總和)路徑。 在通過樹重復出現的同時,我想將路徑方向(分別為“l”或“r”分別為左右)附加到一個列表中,該列表可以在代碼中稍后調用。

到目前為止,我設法正確獲得最大路徑(節點的最大總和)和第一個路徑方向,但不是完整路徑。

我覺得我已接近完成這項任務,只需要在正確的方向上提示。

def sum_max_path(root):

    if not root:
        return

    if root.left is None:
        l_sum = 0
    else:
        l_sum = sum_max_path(root.left)

    if root.right is None:
        r_sum = 0
    else:
        r_sum = sum_max_path(root.right)

    if l_sum > r_sum:
        root.list.append("l")
        return root.value + l_sum
    elif l_sum < r_sum:
        root.list.append("r")
        return root.value + r_sum
    else:
        root.list.append("l")
        return root.value + l_sum

    return root.value + max(l_sum, r_sum)

return sum_max_path(root), root.list

這個輸出是:

The total value in this path is: 8
The largest value path is: ['l']

如果輸出為:我想要的是:

The largest value path is ['l', 'r', 'l'] 

(顯然取決於路徑基於生成的樹的長度)。

不要靜態存儲路徑,而是將其傳遞給每個遞歸調用並從中返回:

def max_sum(node, path):
    ls = rs = 0
    lp = rp = path
    if node.left:
        ls, lp = max_sum(node.left, path + ['l'])
    if node.right:
        rs, rp = max_sum(node.right, path + ['r'])
    ls += node.value
    rs += node.value
    return (ls, lp) if ls > rs else (rs, rp)

完整的例子:

class Node:
    def __init__(self, value, left=None, right=None):
        self.value = value
        self.left = left
        self.right = right


tree = Node(
    1,
    Node(
        9,
        Node(2),
        Node(3)
    ),
    Node(
        8,
        Node(2),
        Node(
            5,
            Node(3),
            Node(2)
        )
    )
)


def max_sum(node, path):
    ls = rs = 0
    lp = rp = path
    if node.left:
        ls, lp = max_sum(node.left, path + ['l'])
    if node.right:
        rs, rp = max_sum(node.right, path + ['r'])
    ls += node.value
    rs += node.value
    return (ls, lp) if ls > rs else (rs, rp)


print(max_sum(tree, []))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM