I want to traverse a Binary Tree with minimum cost, where cost of each edge is 1.
Traversal is complete when each node of the tree is visited.
For instance, the minimum cost of the traversal of following tree is 13.
*
/ \
* *
/ \ \
* * *
/ / \
* * *
the minimum cost of the traversal of following tree is 12.
*
/ \
* *
/ \ \
* * *
/ \
* *
/
*
The cost of traversing the tree is
n-1wherenis the number of nodes.This is true because every tree has exactly
n-1edges – and you need to use all of them in order to visit all the nodes.To be exact it is known that the next 3 statements are equivalent for a graph
Twithnnodes:From the above we can conclude, that in a tree, in order to get to all nodes we must use all edges (because there are no cycles, so no redundant edges) – and there are EXACTLY
n-1of those.EDIT:
From your example it seems you are also counting the times you go back from each edge (i.e. some edges are counted twice).
Well, in this case the optimal solution will be:
Explanation/proof guidelines:
There are
n-1edges exactly in the tree. Each of them is traversed exactly twice except those that leads from the root to the deepest node.You must use each edge (except the mentioned) exactly twice, because with exception of the last branch – you go back from each node.
Since there are exactly
heightedges in the last branch, you get total ofcost = (n-1)*2 - heightNote that it is basically the same as you got: