简体   繁体   中英

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:

  1. base case when node is a leaf return 0.
  2. for every child c of the node recursively compute the cost.
  3. add up all those cost and also add the edge cost twice from node to child twice(as we need to backtrack).
  4. 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).

Is this approach correct?

Is there a better way to solve the problem?

  1. Visit all subtree from a node and returns to the node, it will cost all edges * 2 which belongs to that subtree.
  2. So we should find a path in the tree which the cost of the path is maximum. We just go through the path, and if the we meet some nodes which is not in the path, we just visit it and returns . So The edge in the path will visit only once, and the remain edges will visit twice.
  3. How to find the path with maximum cost? Since it's a tree, you can find it recursively.

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.

2- We will need to find out which leaf node has the highest cost attached to visit root node.

3- once we find this we will need to make our traversal such that this leaf node is the last visited node.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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