简体   繁体   English

在递归查找最大路径总和时,附加二叉树的左或右方向

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

I am creating python code to identify the largest (sum of nodes) path of a binary tree. 我正在创建python代码来识别二叉树的最大(节点总和)路径。 Whilst recurring through the tree, I'd like to append the path direction (either "l" or "r" for left and right respectively) into a list that can be called later in the code. 在通过树重复出现的同时,我想将路径方向(分别为“l”或“r”分别为左右)附加到一个列表中,该列表可以在代码中稍后调用。

So far I'm managed to correctly get the largest path (max sum of nodes) and the first path direction, but not the full path. 到目前为止,我设法正确获得最大路径(节点的最大总和)和第一个路径方向,但不是完整路径。

I feel like I'm close to getting this done, just need a hint in the right direction. 我觉得我已接近完成这项任务,只需要在正确的方向上提示。

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 output of this is: 这个输出是:

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

What I'd like if for the output to be: 如果输出为:我想要的是:

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

(Obviously depending on how long the path is based on the generated tree). (显然取决于路径基于生成的树的长度)。

Do not store the path statically, instead pass it to and return it from each recursive invocation: 不要静态存储路径,而是将其传递给每个递归调用并从中返回:

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)

Complete example: 完整的例子:

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