[英]Find minimum cost to visit all nodes of a tree
Given the root of a tree where each edge has an associated cost. 给定树的根,其中每个边具有相关的成本。 Find the minimum cost to visit every node of the tree.
找到访问树的每个节点的最低成本。
A recursive solution that came to my mind is: 我想到的一个递归解决方案是:
Is this approach correct? 这种方法是否正确?
Is there a better way to solve the problem? 有没有更好的方法来解决这个问题?
edges * 2
which belongs to that subtree. edges * 2
。 The answer should be: 答案应该是:
sum(cost(edge)*2) - sum(edge which in the path)
I checked your solution, I think it's wrong(If I misunderstand your solution, please leave a comment): 我检查了你的解决方案,我认为这是错误的(如果我误解了你的解决方案,请发表评论):
subtract the edge cost of the child that has maximum cost.("greedy" - we > don't want to backtrack from the child that has maximum cost).
减去具有最高成本的孩子的边缘成本。(“贪婪” - 我们>不想从具有最高成本的孩子回溯 )。
That child will be a tree, and some edges must visit twice. 那个孩子将是一棵树,一些边缘必须访问两次。 For example:
例如:
A
/ \
B C
/ \
D E
You can't visit that subtree all edges once to visit all nodes. 您无法访问该子树所有边缘一次访问所有节点。
1- All the nodes-paths will be visited twice except the last leaf node. 1-除最后一个叶节点外,将访问所有节点路径两次。
2- We will need to find out which leaf node has the highest cost attached to visit root node. 2-我们需要找出哪个叶子节点附加了最高成本才能访问根节点。
3- once we find this we will need to make our traversal such that this leaf node is the last visited node. 3-一旦我们发现这一点,我们将需要进行遍历,使得该叶节点是最后访问的节点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.