×

Given a Binary Tree Print the Shortest Path

Implementation

// Writing a program in C++ to find the shortest between the nodes i and j. 
#include <bits/stdc++.h>
using namespace std;


// the given function will print the path between nodes i and j.
void Short__Path(int i, int j, int k, int m, int n)
{
	// The path1 of the function generally stores the path of the node i to lca, and path2 generally stores the path of the node j to lca.  
	vector<int> path1, path2;
	int x = m - 1;


	// we have to push node i into path1.
	path1.push_back(i);


	// Then we must keep pushing the parent node mentioned as i to path1 until we reach the lca. 
	while (x != k) {
		path1.push_back(i / 2);
		i = i / 2;
		x--;
	}
	int y = n - 1;


	// we have to push node j into path2.
	path2.push_back(j);


	// Then we must keep pushing the parent node mentioned as j to path2 until we reach the lca. 
	while (y != k)
	{
		path2.push_back(j / 2);
		j = j / 2;
		y--;
	}


	// Now, we will print the path of node i to lca. 
	for (int l = 0; l < path1.size(); l++)
		cout << path1[l] << " ";


	// Now, we will print the path from lca to node j.
	for (int l = path2.size() - 2; l >= 0; l--)
		cout << path2[l] << " ";
	cout << endl;
}


// After this, we will return the shortest or closest distance between the nodes mentioned as i and j. 
int Shortest__Dist(int i, int j)
{
	// We are creating a vector that will help us store the binary form of the nodes, i.e., i and j. 
	vector<int> v1, v2;


	// searching the binary form of the 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;
	}


	// We know that the binary form will be in reverse order, so we have to reverse the vectors. 
	reverse(v1.begin(), v1.end());
	reverse(v2.begin(), v2.end());


	// Now, we are supposed to find the k value, the 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++;
	}


	Short__Path(p1, p2, k - 1, m, n);
	return m + n - 2 * k;
}


// writing the main code
int main()
{
	cout << Shortest__Dist(1, 2) << endl;
	cout << Shortest__Dist(4, 3) << endl;
	return 0;
}

Output:

Given a binary tree print the shortest path

Example 2

// Writing a program in C# language to find out the shortest between the nodes i and j. 
using System;
using System.Collections.Generic;
	
class TFT
{
// the given function will print the path between nodes i and j.
static void Short__Path(int i, int j, int k, int m,
									int n)
{
	// The path1 of the function generally stores the path of the node i to lca, and path2 generally stores the path of the node j to lca.  
	List<int> path1=new List<int>(),
					path2=new List<int>();
	int x = m - 1;
// we have to push node i into path1. 
	path1.Add(i);
// Then we must keep pushing the parent node mentioned as i to path1 until we reach the lca. 
	while (x != k)
	{
		path1.Add(i / 2);
		i = i / 2;
		x--;
	}
	int y = n - 1;
// we have to push node j into path2.
	path2.Add(j);
// Then we must keep pushing the parent node mentioned as j to path2 until we reach the lca. 
	while (y != k)
	{
		path2.Add(j / 2);
		j = j / 2;
		y--;
	}
// Now, we will print the path of node i to lca. 
	for (int l = 0; l < path1.Count; l++)
		Console.Write( path1[l] + " ");
// Now, we will print the path from lca to node j.
	for (int l = path2.Count - 2; l >= 0; l--)
		Console.Write( path2[l] + " ");
	Console.WriteLine();
}
// After this, we will return the shortest or closest distance between the nodes mentioned as i and j. 
static int Shortest__Dist(int i, int j)
{
// We are creating a vector that will help us store the binary form of the nodes, i.e., i and j. 
	List<int> v1=new List<int>(),
					v2=new List<int>();
// searching the binary form of the 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;
	}
// We know that the binary form will be in reverse order, so we have to reverse the vectors. 
	v1.Reverse();
	v2.Reverse();
// Now, we are supposed to find the k value, the 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++;
	}


	Short__Path(p1, p2, k - 1, m, n);
	return m + n - 2 * k;
}
// writing the main code
public static void Main(String []args)
{
	Console.WriteLine( Shortest__Dist(1, 2) );
	Console.WriteLine(Shortest__Dist(4, 3) );
}
}

Output:

Given a binary tree print the shortest path

Example 3

// Writing a program in Java to find the shortest between the nodes i and j. 
import java.util.*;


class TFT
{
// the given function will print the path between nodes i and j.
static void Short__Path(int i, int j, int k, int m,
									int n)
{
	// The path1 of the function generally stores the path of the node i to lca, and path2 generally stores the path of the node j to lca.  
	Vector<Integer> path1=new Vector<Integer>(),
					path2=new Vector<Integer>();
	int x = m - 1;
// we have to push node i into path1.
	path1.add(i);


	// Then we must keep pushing the parent node mentioned as i to path1 until we reach the lca. 
	while (x != k)
	{
		path1.add(i / 2);
		i = i / 2;
		x--;
	}
	int y = n - 1;
// we have to push node j into path2.
	path2.add(j);
// Then we must keep pushing the parent node mentioned as j to path2 until we reach the lca. 
	while (y != k)
	{
		path2.add(j / 2);
		j = j / 2;
		y--;
	}


	// Now, we will print the path of node i to lca. 
	for (int l = 0; l < path1.size(); l++)
		System.out.print( path1.get(l) + " ");
// Now, we will print the path from lca to node j.
	for (int l = path2.size() - 2; l >= 0; l--)
		System.out.print( path2.get(l) + " ");
	System.out.println();
}
// After this, we will return the shortest or closest distance between the nodes mentioned as i and j. 
static int Shortest__Dist(int i, int j)
{
// We are creating a vector that will help us store the nodes' binary form, i.e., i and j. 
	Vector<Integer> v1=new Vector<Integer>(),
					v2=new Vector<Integer>();
// searching the binary form of the 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;
	}
// We know that the binary form will be in reverse order, so we have to reverse the vectors. 
	Collections.reverse(v1);
	Collections.reverse(v2);
// Now, we are supposed to find the k value, the 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++;
	}


	Short__Path(p1, p2, k - 1, m, n);
	return m + n - 2 * k;
}
// writing the main code
public static void main(String args[])
{
	System.out.println( Shortest__Dist(1, 2) );
	System.out.println(Shortest__Dist(4, 3) );
}
}

Output:

Given a binary tree print the shortest path

Example 4

<script>
// Writing a program in Javascript language to find out the shortest between the nodes i and j. 
function Short__Path(i,j,k,m,n)
{
	// the given function will print the path between nodes i and j.
// The path1 of the function generally stores the path of the node i to lca, and path2 generally stores the path of the node j to lca.  
	let path1=[];
	let path2=[];
	let x = m - 1;
// we have to push node i into path1.
	path1.push(i);
// Then we must keep pushing the parent node mentioned as i to path1 until we reach the lca. 
	while (x != k)
	{
		path1.push(Math.floor(i / 2));
		i = Math.floor(i / 2);
		x--;
	}
	let y = n - 1;
// we have to push node j into path2.
	path2.push(j);
// Then we must keep pushing the parent node mentioned as j to path2 until we reach the lca. 
	while (y != k)
	{
		path2.push(Math.floor(j / 2));
		j = Math.floor(j / 2);
		y--;
	}
// Now, we will print the path of node i to lca. 
	for (let l = 0; l < path1.length; l++)
		document.write( path1[l] + " ");
// Now, we will print the path from lca to node j.
	for (let l = path2.length - 2; l >= 0; l--)
		document.write( path2[l] + " ");
	document.write("<br>");
}
// After this, we will return the shortest or closest distance between the nodes mentioned as i and j. 
function Shortest__Dist(i,j)
{
	// We are creating a vector that will help us store the nodes' binary form, i.e., i and j. 
	let v1=[];
	let v2=[];
// searching the binary form of the 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);
	}
// We know that the binary form will be in reverse order, so we have to reverse the vectors. 
	v1.reverse();
	v2.reverse();
// Now, we are supposed to find the k value, the 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++;
	}


	Short__Path(p1, p2, k - 1, m, n);
	return m + n - 2 * k;
}
// writing the main code
document.write( Shortest__Dist(1, 2) +"<br>");
document.write(Shortest__Dist(4, 3) +"<br>");
</script>

Output:

Given a binary tree print the shortest path

Related Topics

Data Structures Tutorial

The data structure is a way of storing and organizing data in a computer system. So that we can use the data quickly, which means the information is stored and...

7 minutes read.

Count pairs from two linked lists whose sum is equal to a given value

Count pairs from two linked lists whose sum is equal to a given value In this problem, we have given two linked lists of size n1 and n2 with distinct elements...

4 minutes read.

Given Two Binary Trees, Check if it is Symmetric

Implementation // creating a C++ program that will help us check whether the two given trees are mirror images of each other.  #include<bits/stdc++.h> using namespace std; /* A given binary tree has a data...

5 minutes read.

Insertion Sort in Data Structures

Insertion Sort in C++ Insertion sort is a sorting algorithm that, in each iteration, installs an unsorted element in its proper position Insertion sort operates in a similar way to how we...

3 minutes read.

B Tree in Data Structure

Data management is called database management. A data model is a system that stores, manages, and optimizes computer resources. Data processing is not just about data storage. Almost every app...

9 minutes read.

FLEX (Fast Lexical Analyzer Generator)

FLEX stands for Fast Lexical Analyzer Generator. Around 1987, Vern Paxson created Flex in C with a great deal of input and inspiration from Van Jacobson. Van Jacobson's approach is...

3 minutes read.

Breadth First Search

Breadth First Search Breadth first search is a graph traversing algorithm. In this, we start traversing from the source node or any selected node and traverse the graph layer by layer....

6 minutes read.

Rearrange a linked list into alternate fashion first and the last element

Rearrange a linked list into alternate fashion first and the last element This article will explain how to rearrange the linked list into alternate fashion first and the last element. Here,...

3 minutes read.

Bucket Sort

Bucket Sort: In the sorting algorithm, we create buckets and put elements into them. We can apply some sorting algorithm (insertion sort) to sort the elements in each bucket. Finally,...

4 minutes read.

Recursion - Factorial and Fibonacci

In this article, we will learn how to find the factorial of a number and the Fibonacci series up to n using the recursion method. What is recursion? Defining anything in terms...

7 minutes read.

Construction of B tree in Data Structure

A B-tree is a type of balanced tree data structure that is commonly used in file systems and databases to improve the efficiency of search, insert, and delete operations. The structure...

4 minutes read.

CSS Text-indent

Text-indent The Text-indent property of CSS is used to set any first line’s indentation inside a text’s block. It describes the horizontal space amount that puts establish before the text line. It...

3 minutes read.

Queue Implementation using stacks Data Structure

Queue Implementation using stacks In this problem, we have stack data structure which supports only push() and pop() operations. We are required to implement a queue data structure using the instances...

4 minutes read.

Convert binary tree to a doubly linked list

Implementation //creating a C++ program for the transition of a binary tree into a linked list. #include <iostream> using namespace std; /* Firstly, let’s create a binary tree that will help us in setting...

4 minutes read.

Bubble sort algorithm using Javascript

Sorting is a very useful technique in many algorithms and programs. Basically, sorting operations help us to arrange a set of data in a particular manner. Bubble sort is one...

3 minutes read.

Red Black Tree vs AVL Tree: Data Structure

Difference Between Red Black Tree vs AVL Tree Red Black Tree: A red-black tree is referred as self-balancing binary search tree. In red-black, each node stores an extra bit that determines...

4 minutes read.

LCA of binary tree

Implementation //Writing a program to find the lowest common factor in a given binary search tree. #include <iostream> #include <vector> using namespace std; // the very first step is to create a binary tree. struct __nod { int...

8 minutes read.

Deletion in B+ Tree

Make a search for the leaf node that containing the key value by taking the value in a key value. If the required key value is found, then it will remove...

6 minutes read.

Stack vs Array

Difference between Array and Stack In this article, we are going to discuss the major differences between the stack and array data structures: Array – In the data structure, the array is...

3 minutes read.

Delete the Middle element of the Linked List in C

Delete the Middle element of the Linked List in C This article has given a singly linked list and will delete the middle element of the given linked list. Example:  The given...

3 minutes read.