Given a binary tree, the task is to find the distance between two keys in a binary tree, no parent pointers are given. The distance between two nodes is the minimum number of edges to be traversed to reach one node from other.
We have already discussed a method which uses segment tree to reduce the query time to O(logn), here the task is to reduce query time to O(1) by compromising with space complexity to O(nlogn). In this post, we will use Sparse table instead of segment tree for finding the minimum in given range, which uses dynamic programming and bit manipulation to achieve O(1) query time.
A sparse table will preprocess the minimum values of given range for L array in Nlogn space i.e. each node will contain chain of values of log(i) length where i is the index of the ith node in L array. Each entry in the sparse table says M[i][j] will represent the index of the minimum value in the subarray starting at i having length 2^j.
The distance between two nodes can be obtained in terms of lowest common ancestor.
Dist(n1, n2) = Level[n1] + Level[n2] - 2*Level[lca]
This problem can be breakdown into:
- Finding levels of each node
- Finding the Euler tour of binary tree
- Building sparse table for LCA.
These steps are explained below :
- Find the levels of each node by applying level order traversal.
- Find the LCA of two nodes in binary tree in O(logn) by Storing Euler tour of Binary tree in array and computing two other arrays with the help of levels of each node and Euler tour.
These steps are shown below:
(I) First, find Euler Tour of binary tree.
(II) Then, store levels of each node in Euler array.
(III) Then, store First occurrences of all nodes of binary tree in Euler array. H stores the indices of nodes from Euler array, so that range of query for finding minimum can be minimized and their by further optimizing the query time.
- Then build sparse table on L array and find the minimum value say X in range (H[A] to H[B]). Then, we use the index of value X as an index to Euler array to get LCA, i.e. Euler[index(X)].
Let, A=8 and B=5.
(I) H= 1 and H=2
(II) we get min value in L array between 1 and 2 as X=0, index=7
(III) Then, LCA= Euler, i.e LCA=1.
- Finally, apply distance formula discussed above to get the distance between two nodes.
Dist(4, 5) = 2 Dist(4, 6) = 4 Dist(3, 4) = 3 Dist(2, 4) = 1 Dist(8, 5) = 5
Time Complexity: O(1)
Space Complexity: O(N log N)