4

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?

Sayakiss
  • 6,878
  • 8
  • 61
  • 107
Prashant Bhanarkar
  • 930
  • 3
  • 14
  • 32
  • I find the problem description a bit confusing; how exactly would a 'visit' look like? Apparently, the proposed algorithm computes twice the sum of all edge weights. – Codor Apr 27 '16 at 07:38
  • Isn't that what [minimum weight spanning tree](https://en.wikipedia.org/wiki/Minimum_spanning_tree) means. There are algorithms defined on this page, you can go through those ones. – imharindersingh Apr 27 '16 at 17:20
  • @harindersingh I don't have to find the minimum weight spanning tree. – Prashant Bhanarkar Apr 28 '16 at 19:11

2 Answers2

5
  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.

Sayakiss
  • 6,878
  • 8
  • 61
  • 107
0

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.

  • It is also possible that the _first_ visited node is also a leaf; if the tree is a line graph, the optimal solution will be uniquely determinded (namely all of the edged); both the first and the last visited nodes will be a leaf. – Codor Apr 27 '16 at 08:09