[英]Maximum weight edge sum from root node in a binary weighted tree
You are given a binary weighted tree find the maximum weight edge sum from root node.你得到一个二叉加权树,从根节点找到最大权重边和。
Following is the tree.下面是树。 Maximum weight starting from root node is 9. Explanation: Node 1->Node 3 Weight = 6 and Node 3->Node-6 Weight = 3. Total Weight = 6+3 = 9
从根节点开始的最大权重为 9。解释:节点 1->节点 3 权重 = 6 和节点 3->节点-6 权重 = 3。总权重 = 6+3 = 9
You can use any traversal method.您可以使用任何遍历方法。 A* would find the path with least number of node visits, but it requires extra memory.
A* 会找到节点访问次数最少的路径,但它需要额外的 memory。 I would go for a simple depth-first traversal (using recursion) and just keep track of the maximum found.
我会 go 进行简单的深度优先遍历(使用递归)并跟踪找到的最大值。
Let's assume your tree is defined like this:假设您的树是这样定义的:
from collections import namedtuple
Edge = namedtuple("Edge", "weight,node")
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
tree = Node(1, Edge(4, Node(2, Edge(1, Node(4)),
Edge(1, Node(5)))),
Edge(6, Node(3, Edge(3, Node(6)),
Edge(0, Node(7)))))
...then you can add this method to your Node
class: ...然后您可以将此方法添加到您的
Node
class:
def maxweight(self):
return max(self.left.weight + self.left.node.maxweight() if self.left else 0,
self.right.weight + self.right.node.maxweight() if self.right else 0)
and call it as:并将其称为:
print(tree.maxweight())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.