c++tree

Finding path between 2 tree nodes


how can i print the path between any 2 query nodes in a tree not necessary a binary tree? I have been using dfs and storing the paths in a vector for each query and printing it. But if input query no. is too large q<=10^5,my algorithm which is of o(nq)(may be not sure) complexity fails.n=no of nodes in the tree.Can anyone help me with some better optimization so that the time complexity reduces may be o(nlogq) or o(q*logn).n<=10^5.If any precomputation required suggest me so.


Solution

  • Have you looked at using either the UCS or A* algorithms? A* with a good heuristic will allow you to visit the least amount of nodes