Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Tree
  • Practice Tree
  • MCQs on Tree
  • Tutorial on Tree
  • Types of Trees
  • Basic operations
  • Tree Traversal
  • Binary Tree
  • Complete Binary Tree
  • Ternary Tree
  • Binary Search Tree
  • Red-Black Tree
  • AVL Tree
  • Full Binary Tree
  • B-Tree
  • Advantages & Disadvantages
Open In App
Next Article:
XOR of path between any two nodes in a Binary Tree
Next article icon

Shortest path between two nodes in array like representation of binary tree

Last Updated : 12 Apr, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Consider a binary tree in which each node has two children except the leaf nodes. If a node is labeled as ‘v’ then its right children will be labeled as 2v+1 and left children as 2v. Root is labelled as
Given two nodes labeled as i and j, the task is to find the shortest distance and the path from i to j. And print the path of node i and node j from root node.

Examples: 

Input : i = 1, j = 2        
Output : 1
Explanation:
Path is 1 2

Input: i = 4, j = 3
Output : 3
Explanation:
Path is 4 2 1 3


This problem is mainly an extension of Find distance between two given keys of a Binary Tree. Here we not only find the shortest distance but also the path.
The distance between the two nodes i and j will be equal to dist(i, LCA(i, j)) + dist(j, LCA(i, j)) where LCA means the lowest common ancestor of nodes labeled as i and j. If a number x is represented in the binary form then 2*x can be represented by appending 0 to the binary representation of x and 2x+1 can be represented by appending 1 to the binary representation of x. This is because when we append 0 all the terms present in the binary form of x shift left, so it gets doubled similarly when we append 1, we get 2x+1. Suppose the binary representation of a node is 1010 this tells us the path of this node from root. First-term ‘1’ represents root second term 0 represents left turn then the third term 1 represents a right turn from the previous node and finally, 0 represents the left turn. 

Node 10 in binary form is 1010 and 13 in binary form is 1101 secondly length of the binary representation of any node also tells about its level in a binary tree. Suppose binary representation of i is m length and is [Tex]i_1          [/Tex][Tex]i_2          [/Tex]…[Tex]i_m          [/Tex]and binary representation of node j is n length [Tex]j_1          [/Tex][Tex]j_2          [/Tex]……[Tex]j_n          [/Tex]. 
Thus we know the path of i and j from the root. Find out k such that for all p<=k [Tex]i_p          [/Tex]= [Tex]j_p          [/Tex]. This is the LCA of i and j in binary form.So dist(i, LCA(i, j)) will be m – k and dist(j, LCA(i, j)) = n – k. so answer will be m + n – 2k. And printing the path is also not a big issue just store the path of i to LCA and path of j to LCA and concatenate them.

C++

// C++ representation of finding shortest
// distance between node i and j
#include <bits/stdc++.h>
using namespace std;
 
// prints the path between node i and node j
void ShortestPath(int i, int j, int k, int m, int n)
{
    // path1 stores path of node i to lca and
    // path2 stores path of node j to lca
    vector<int> path1, path2;
    int x = m - 1;
 
    // push node i in path1
    path1.push_back(i);
 
    // keep pushing parent of node labelled
    // as i to path1 until lca is reached
    while (x != k) {
        path1.push_back(i / 2);
        i = i / 2;
        x--;
    }
    int y = n - 1;
 
    // push node j to path2
    path2.push_back(j);
 
    // keep pushing parent of node j till
    // lca is reached
    while (y != k)
    {
        path2.push_back(j / 2);
        j = j / 2;
        y--;
    }
 
    // printing path from node i to lca
    for (int l = 0; l < path1.size(); l++)
        cout << path1[l] << " ";
 
    // printing path from lca to node j
    for (int l = path2.size() - 2; l >= 0; l--)
        cout << path2[l] << " ";
    cout << endl;
}
 
// returns the shortest distance between
// nodes labelled as i and j
int ShortestDistance(int i, int j)
{
    // vector to store binary form of i and j
    vector<int> v1, v2;
 
    // finding binary form of i and j
    int p1 = i;
    int p2 = j;
    while (i != 0)
    {
        v1.push_back(i % 2);
        i = i / 2;
    }
    while (j != 0) {
        v2.push_back(j % 2);
        j = j / 2;
    }
 
    // as binary form will be in reverse order
    // reverse the vectors
    reverse(v1.begin(), v1.end());
    reverse(v2.begin(), v2.end());
 
    // finding the k that is lca (i, j)
    int m = v1.size(), n = v2.size(), k = 0;
    if (m < n)
    {
        while (k < m && v1[k] == v2[k])
            k++;
    }
    else {
        while (k < n && v1[k] == v2[k])
            k++;
    }
 
    ShortestPath(p1, p2, k - 1, m, n);
    return m + n - 2 * k;
}
 
// Driver Code
int main()
{
    cout << ShortestDistance(1, 2) << endl;
    cout << ShortestDistance(4, 3) << endl;
    return 0;
}
                      
                       

Java

// Java representation of finding shortest
// distance between node i and j
import java.util.*;
 
class GFG
{
     
// prints the path between node i and node j
static void ShortestPath(int i, int j, int k, int m,
                                    int n)
{
    // path1 stores path of node i to lca and
    // path2 stores path of node j to lca
    Vector<Integer> path1=new Vector<Integer>(),
                    path2=new Vector<Integer>();
    int x = m - 1;
 
    // push node i in path1
    path1.add(i);
 
    // keep pushing parent of node labelled
    // as i to path1 until lca is reached
    while (x != k)
    {
        path1.add(i / 2);
        i = i / 2;
        x--;
    }
    int y = n - 1;
 
    // push node j to path2
    path2.add(j);
 
    // keep pushing parent of node j till
    // lca is reached
    while (y != k)
    {
        path2.add(j / 2);
        j = j / 2;
        y--;
    }
 
    // printing path from node i to lca
    for (int l = 0; l < path1.size(); l++)
        System.out.print( path1.get(l) + " ");
 
    // printing path from lca to node j
    for (int l = path2.size() - 2; l >= 0; l--)
        System.out.print( path2.get(l) + " ");
    System.out.println();
}
 
// returns the shortest distance between
// nodes labelled as i and j
static int ShortestDistance(int i, int j)
{
    // vector to store binary form of i and j
    Vector<Integer> v1=new Vector<Integer>(),
                    v2=new Vector<Integer>();
 
    // finding binary form of i and j
    int p1 = i;
    int p2 = j;
    while (i != 0)
    {
        v1.add(i % 2);
        i = i / 2;
    }
    while (j != 0)
    {
        v2.add(j % 2);
        j = j / 2;
    }
 
    // as binary form will be in reverse order
    // reverse the vectors
    Collections.reverse(v1);
    Collections.reverse(v2);
 
    // finding the k that is lca (i, j)
    int m = v1.size(), n = v2.size(), k = 0;
    if (m < n)
    {
        while (k < m && v1.get(k) == v2.get(k))
            k++;
    }
    else
    {
        while (k < n && v1.get(k) == v2.get(k))
            k++;
    }
 
    ShortestPath(p1, p2, k - 1, m, n);
    return m + n - 2 * k;
}
 
// Driver code
public static void main(String args[])
{
    System.out.println( ShortestDistance(1, 2) );
    System.out.println(ShortestDistance(4, 3) );
}
}
 
// This code is contributed by Arnab Kundu
                      
                       

Python3

# Python3 representation of finding
# shortest distance between node i and j
 
# Prints the path between node i and node j
def ShortestPath(i, j, k, m, n):
 
    # path1 stores path of node i to lca and
    # path2 stores path of node j to lca
    path1, path2 = [], []
    x = m - 1
 
    # push node i in path1
    path1.append(i)
 
    # keep pushing parent of node labelled
    # as i to path1 until lca is reached
    while x != k:
        path1.append(i // 2)
        i = i // 2
        x -= 1
     
    y = n - 1
 
    # push node j to path2
    path2.append(j)
 
    # keep pushing parent of node
    # j till lca is reached
    while y != k:
        path2.append(j / 2)
        j = j // 2
        y -= 1
     
    # printing path from node i to lca
    for l in range(0, len(path1)):
        print(path1[l], end=" ")
 
    # printing path from lca to node j
    for l in range(len(path2) - 2, -1, -1):
        print(path2[l], end=" ")
    print()
 
# Returns the shortest distance
# between nodes labelled as i and j
def ShortestDistance(i, j):
 
    # vector to store binary form of i and j
    v1, v2 = [], []
 
    # finding binary form of i and j
    p1, p2 = i, j
    while i != 0:
        v1.append(i % 2)
        i = i // 2
     
    while j != 0:
        v2.append(j % 2)
        j = j // 2
     
    # as binary form will be in reverse
    # order reverse the vectors
    v1 = v1[::-1]
    v2 = v2[::-1]
 
    # finding the k that is lca (i, j)
    m, n, k = len(v1), len(v2), 0
    if m < n:
        while k < m and v1[k] == v2[k]:
            k += 1
     
    else:
        while k < n and v1[k] == v2[k]:
            k += 1
     
    ShortestPath(p1, p2, k - 1, m, n)
    return m + n - 2 * k
 
# Driver Code
if __name__ == "__main__":
 
    print(ShortestDistance(1, 2))
    print(ShortestDistance(4, 3))
 
# This code is contributed by Rituraj Jain
                      
                       

C#

// C#  representation of finding shortest
// distance between node i and j
using System;
using System.Collections.Generic;   
     
class GFG
{
      
// prints the path between node i and node j
static void ShortestPath(int i, int j, int k, int m,
                                    int n)
{
    // path1 stores path of node i to lca and
    // path2 stores path of node j to lca
    List<int> path1=new List<int>(),
                    path2=new List<int>();
    int x = m - 1;
  
    // push node i in path1
    path1.Add(i);
  
    // keep pushing parent of node labelled
    // as i to path1 until lca is reached
    while (x != k)
    {
        path1.Add(i / 2);
        i = i / 2;
        x--;
    }
    int y = n - 1;
  
    // push node j to path2
    path2.Add(j);
  
    // keep pushing parent of node j till
    // lca is reached
    while (y != k)
    {
        path2.Add(j / 2);
        j = j / 2;
        y--;
    }
  
    // printing path from node i to lca
    for (int l = 0; l < path1.Count; l++)
        Console.Write( path1[l] + " ");
  
    // printing path from lca to node j
    for (int l = path2.Count - 2; l >= 0; l--)
        Console.Write( path2[l] + " ");
    Console.WriteLine();
}
  
// returns the shortest distance between
// nodes labelled as i and j
static int ShortestDistance(int i, int j)
{
    // vector to store binary form of i and j
    List<int> v1=new List<int>(),
                    v2=new List<int>();
  
    // finding binary form of i and j
    int p1 = i;
    int p2 = j;
    while (i != 0)
    {
        v1.Add(i % 2);
        i = i / 2;
    }
    while (j != 0)
    {
        v2.Add(j % 2);
        j = j / 2;
    }
  
    // as binary form will be in reverse order
    // reverse the vectors
    v1.Reverse();
    v2.Reverse();
  
    // finding the k that is lca (i, j)
    int m =v1.Count, n =v2.Count, k = 0;
    if (m < n)
    {
        while (k < m && v1[k] == v2[k])
            k++;
    }
    else
    {
        while (k < n && v1[k] == v2[k])
            k++;
    }
  
    ShortestPath(p1, p2, k - 1, m, n);
    return m + n - 2 * k;
}
  
// Driver code
public static void Main(String []args)
{
    Console.WriteLine( ShortestDistance(1, 2) );
    Console.WriteLine(ShortestDistance(4, 3) );
}
}
 
// This code is contributed by Princi Singh
                      
                       

Javascript

<script>
 
// Javascript  representation of finding shortest
// distance between node i and j
 
// prints the path between node i and node j
function ShortestPath(i,j,k,m,n)
{
    // path1 stores path of node i to lca and
    // path2 stores path of node j to lca
    let path1=[];
    let path2=[];
    let x = m - 1;
   
    // push node i in path1
    path1.push(i);
   
    // keep pushing parent of node labelled
    // as i to path1 until lca is reached
    while (x != k)
    {
        path1.push(Math.floor(i / 2));
        i = Math.floor(i / 2);
        x--;
    }
    let y = n - 1;
   
    // push node j to path2
    path2.push(j);
   
    // keep pushing parent of node j till
    // lca is reached
    while (y != k)
    {
        path2.push(Math.floor(j / 2));
        j = Math.floor(j / 2);
        y--;
    }
   
    // printing path from node i to lca
    for (let l = 0; l < path1.length; l++)
        document.write( path1[l] + " ");
   
    // printing path from lca to node j
    for (let l = path2.length - 2; l >= 0; l--)
        document.write( path2[l] + " ");
    document.write("<br>");
}
 
// returns the shortest distance between
// nodes labelled as i and j
function ShortestDistance(i,j)
{
    // vector to store binary form of i and j
    let v1=[];
    let v2=[];
   
    // finding binary form of i and j
    let p1 = i;
    let p2 = j;
    while (i != 0)
    {
        v1.push(i % 2);
        i = Math.floor(i / 2);
    }
    while (j != 0)
    {
        v2.push(j % 2);
        j = Math.floor(j / 2);
    }
   
    // as binary form will be in reverse order
    // reverse the vectors
    v1.reverse();
    v2.reverse();
   
    // finding the k that is lca (i, j)
    let m =v1.length, n =v2.length, k = 0;
    if (m < n)
    {
        while (k < m && v1[k] == v2[k])
            k++;
    }
    else
    {
        while (k < n && v1[k] == v2[k])
            k++;
    }
   
    ShortestPath(p1, p2, k - 1, m, n);
    return m + n - 2 * k;
}
 
// Driver code
document.write( ShortestDistance(1, 2) +"<br>");
document.write(ShortestDistance(4, 3) +"<br>");
 
 
// This code is contributed by avanitrachhadiya2155
</script>
                      
                       

Output: 
 

1 2 1 4 2 1 3 3

Complexity Analysis:
Time Complexity: O([Tex]log_2          [/Tex]i + [Tex]log_2          [/Tex]j) since we are shifting value of i and j to the right for every traversal

Auxiliary Space: O(log_2 i + log_2 j) since we are storing paths for every right shifting values of i and j.




 



Next Article
XOR of path between any two nodes in a Binary Tree

A

Ayush Jha
Improve
Article Tags :
  • DSA
  • Tree
Practice Tags :
  • Tree

Similar Reads

  • Print path between any two nodes in a Binary Tree | Set 2
    Given a Binary Tree of distinct nodes and a pair of nodes. The task is to find and print the path between the two given nodes in the binary tree.Examples: Input: N1 = 7, N2 = 4 Output: 7 3 1 4 Approach: An approach to solve this problem has been discussed in this article. In this article, an even op
    15 min read
  • Print path between any two nodes in a Binary Tree
    Given a Binary Tree of distinct nodes and a pair of nodes. The task is to find and print the path between the two given nodes in the binary tree. For Example, in the above binary tree the path between the nodes 7 and 4 is 7 -> 3 -> 1 -> 4. The idea is to find paths from root nodes to the tw
    12 min read
  • XOR of path between any two nodes in a Binary Tree
    Given a binary tree with distinct nodes and a pair of two nodes. The task is to find the XOR of all of the nodes which comes on the path between the given two nodes. For Example, in the above binary tree for nodes (3, 5) XOR of path will be (3 XOR 1 XOR 0 XOR 2 XOR 5) = 5. The idea is to make use of
    8 min read
  • Queries to find distance between two nodes of a Binary tree
    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
    15+ min read
  • Create Binary Tree from given Array of relation between nodes
    Given a 2D integer array where each row represents the relation between the nodes (relation[i] = [parenti, childi, isLefti]). The task is to construct the binary tree described by the 2D matrix and print the LevelOrder Traversal of the formed Binary Tree. Examples: Input: Relation[] = [[20, 15, 1],
    12 min read
  • Shortest distance between two nodes in an infinite binary tree
    Consider you have an infinitely long binary tree having a pattern as below: 1 / \ 2 3 / \ / \ 4 5 6 7 / \ / \ / \ / \ . . . . . . . . Given two nodes with values x and y. The task is to find the length of the shortest path between the two nodes. Examples: Input: x = 2, y = 3 Output: 2 Input: x = 4,
    15 min read
  • Queries to find distance between two nodes of a Binary tree - O(logn) method
    Given a binary tree, the task is to find the distance between two keys in a binary tree, no parent pointers are given. Distance between two nodes is the minimum number of edges to be traversed to reach one node from other. This problem has been already discussed in previous post but it uses three tr
    15+ min read
  • Find Height of Binary Tree represented by Parent array
    A given array represents a tree in such a way that the array value gives the parent node of that particular index. The value of the root node index would always be -1. Find the height of the tree. The height of a Binary Tree is the number of nodes on the path from the root to the deepest leaf node,
    13 min read
  • Find distance between two nodes of a Binary Tree
    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 another. The given two nodes are guaranteed to be in the binary tree and all nod
    15+ min read
  • Minimum sum path between two leaves of a binary tree
    Given a binary tree in which each node element contains a number. The task is to find the minimum possible sum from one leaf node to another.If one side of root is empty, then function should return minus infinite.Examples: Input : 4 / \ 5 -6 / \ / \ 2 -3 1 8 Output : 1 The minimum sum path between
    10 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences