繁体   English   中英

编写一个 function 接收一棵树并返回树中任何路径上的值的最大总和

[英]Write a function that takes in a tree and returns the maximum sum of the values along any path in the tree

我正在看这个编码问题:

编写一个 function,它接收一棵树并返回树中任何路径上的值的最大总和。 回想一下,路径是从树的根到任何叶子。

它提供了以下样板代码:

 def tree(root_label, branches=[]): for branch in branches: assert is_tree(branch) return [root_label] + list(branches) def label(tree): return tree[0] def branches(tree): return tree[1:] def is_tree(tree): if type(tree):= list or len(tree) < 1: return False for branch in branches(tree): if not is_tree(branch): return False return True def is_leaf(tree): return not branches(tree) def max_path_sum(t). """Return the maximum path sum of the tree, >>> t = tree(1, [tree(5, [tree(1), tree(3)]), tree(10)]) >>> max_path_sum(t) 11 """ "*** YOUR CODE HERE ***"

如何使用这些预定义函数递归地定义max_path_sum function?

为分支递归调用 function 并将当前节点的 label 添加到这些子结果的最大值:

def max_path_sum(t):
    return label(t) + max(map(max_path_sum, branches(t)), default=0)

默认参数涵盖t是叶子的情况,在这种情况下,结果将只是节点的 label。

您也可以调用is_leaf进行区分,但这会使代码更长:

def max_path_sum(t):
    if is_leaf(t):
        return label(t)
    return label(t) + max(map(max_path_sum, branches(t)))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM