S
S
sashx2022-01-03 23:56:01
Python
sashx, 2022-01-03 23:56:01

How to find the distance between vertices in a tree?

Friends, hello! I can't guess, how can I find out the distances between two entered vertices in the tree using DFS? (The tree is undirected and unweighted)

For example from the picture:
The distance between 0 and 15 is three.

61d362cc07d79873350126.png

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexandroppolus, 2022-01-04
@Alexandroppolus

For such business BFS is more convenient.
When adding nodes to the queue, just add the distance to the same place (if the current processed node has a distance of N, then the children in the queue get N + 1)

W
Wataru, 2022-01-04
@wataru

Your tree must be undirected. Just a list of neighboring vertices for each. And there, run DFS or BFS from one vertex, which counts the distance and displays it if you have reached the second vertex.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question