Given a binary tree having N nodes and weight of N-1 edges. The distance between two nodes is the sum of the weight of edges on the path between two nodes. Each query contains two integers U and V, the task is to find the distance between nodes U and V.
Output: 3 5 12 12
Distance between nodes 1 to 3 = weight(1, 3) = 2
Distance between nodes 2 to 3 = weight(1, 2) + weight(1, 3) = 5
Distance between nodes 3 to 5 = weight(1, 3) + weight(1, 2) + weight(2, 5) = 12
Distance between nodes 4 to 5 = weight(4, 2) + weight(2, 5) = 12
- Binary Lifting is a Dynamic Programming approach where we pre-compute an array lca[i][j] where i = [1, n], j = [1, log(n)] and lca[i][j] contains 2j-th ancestor of node i.
- For computing the values of lca, the following recursion may be used
- As we will compute the lca array we will also calculate the distance where distance[i][j] contains the distance from node i to its 2j-th ancestor
- For computing the values of dist, the following recursion may be used.
- After precomputation, we find the distance between (u, v) as we find the least common ancestor of (u, v).
Below is the implementation of the above approach:
3 5 12
Time Complexity: The time taken in pre-processing is O(N logN) and every query takes O(logN) time. Therefore, overall time complexity of the solution is O(N logN).
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price.