# Hints : Three Paths on a Tree

Solve an easier version of the problem first

Given nodes`a`

and`b`

, come up with a Linear time algorithm to compute node`c`

such that the number of edges on atleast one of the three paths is maximised.

`a`

and `b`

. Then, hang the remaining vertices on that rod.
Refer to the image in the next hint for a visualization.
Intuitively, where should should vertex `c`

be? And how to find it optimally?

The deepest node in the forest is node`c`

.

One way to find such a vertex `c`

is to start a BFS from each node lying on the rod (path from `a --> b`

). Then, pick the node with the maximum height amongst them. How to speed it up?

**Multi Source BFS**

Run a multi source BFS with all nodes on the straight line as the source. This would give you the depth of each node in the forest.

How to compute all nodes lying on the path from `a`

to `b`

?

How to compute all nodes lying on the path from `a`

to `b`

?

Answer: Start a BFS from point `a`

, and maintain parent pointers. Then, climb the parent array, starting from `b`

until you reach node `a`

.

`a`

and `b`

?
Intuitively, the end points of the diameter are the best candidates. It can give you the longest rod on which you can hang other nodes. Read this tutorial to learn about Tree Diameter and how to compute it.

Solve CSES: Tree Diameter

(Optional): Solve CSES: Tree Distances 1

- Start a BFS with a random node. Get the farthest vertex, say
`a`

. This is one endpoint of the diameter. - Start a BFS from node
`a`

and get the farthest node, say`b`

. This is the other end of the diameter. - Start a multi source BFS with all nodes on the path from
`a`

to`b`

as source. Then, the deepest node in the tree is`c`

.

If you’re getting a WA with the above approach, read the next hint for a catch.

`c`

is different from node `a`

and `b`

after multi source BFS? Note that distance of all nodes would be zero in multi source BFS.