Given a binary tree with as its root and for any parent its left child will be 2*i and right child will be 2*i+1. The task is to find the minimum distance between two nodes n1 and n2.
1 / \ 2 3 / \ / \ 4 5 6 7 / \ / \ / \ / \ . . . . . . . .
Input : n1 = 7, n2 = 10 Output : 5 Input : n1 = 6, n2 = 7 Output : 4
There are so many ways to find the minimum distance between two given nodes of a binary tree.
Here is an efficient way to find the same with the help of binary representation of given nodes. For any node, take a closer look on its binary representation. For example, consider node 9. Binary representation of 9 is 1001. So to find the path from root to a node, find the binary representation of that node and move from left to right in that binary representation and move to right child in tree if a 1 is encountered and move to left child if a 0 is encountered.
Path of 9 as per bit representation 1 / \ 2 3 /\ /\ 4 5 6 7 /\ 8 9.
Hence, for finding the minimum distance between two nodes, we will try to find the common part of binary representation of both nodes which is actually the common path from root to LCA. Let first k-bits for both node is same. Also, if binary form is of n-bit then it shows that path distance from root to that node is of n length. Hence from above statements we can easily conclude that: If m and n is the bit-length of two nodes and k-starting bits of both node’s value are same then the minimum distance between both node will be: m + n – 2*k.
Note: Last similar bit shows the position of LCA in given binary tree.
Below is the implementation of the above approach:
- Find distance from root to given node in a binary tree
- Find distance between two nodes of a Binary Tree
- Queries to find distance between two nodes of a Binary tree
- Shortest distance between two nodes in an infinite binary tree
- Queries to find distance between two nodes of a Binary tree - O(logn) method
- Print the nodes of binary tree as they become the leaf node
- Convert a Binary Tree such that every node stores the sum of all nodes in its right subtree
- Change a Binary Tree so that every node stores sum of all nodes in left subtree
- Minimum and maximum node that lies in the path connecting two nodes in a Binary Tree
- Print all nodes at distance k from a given node
- Print all nodes that are at distance k from a leaf node
- XOR of all the nodes in the sub-tree of the given node
- Number of leaf nodes in the subtree of every node of an n-ary tree
- Longest Path with Same Values in a Binary Tree
- Create loops of even and odd values in a binary tree
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.