Given a binary tree with n nodes and two node values a and b, find the minimum distance between them. The distance is defined as the minimum number of edges between the two nodes. It is guaranteed that both nodes exist in the binary tree and all node values are unique.
Examples:
Input:
a = 2, b = 3 Output: 2 Explanation: The path between node 2 and node 3 is: 2 -> 1 -> 3.The number of edges in this path is 2, so the minimum distance is 2.
Input:
a = 4, b = 7 Output: 4 Explanation: The path between node 4 and node 7 is: 4 -> 2 -> 1 -> 3 -> 7.The number of edges in this path is 4, so the minimum distance is 4.
Using LCA and Path Length - O(n) Time and O(h) Space
The shortest path between two nodes always goes through their Lowest Common Ancestor (LCA). The idea is to first find the Lowest Common Ancestor (LCA) of the two given nodes in the Binary Tree. Once the LCA is found, the distance between the two nodes can be calculated using their distances from the root.
The distance between two nodes is given by: Dist(a, b) = Dist(root, a) + Dist(root, b) - 2 * Dist(root, LCA) Where: a, b are the given nodes and root is the root of the Binary Tree LCA is the lowest common ancestor of a and b Dist(x, y) represents the number of edges between nodes x and y
This works because the path from root to LCA is counted twice while computing distances of a and b, so we subtract it two times to get the correct distance.
Steps:
Start by traversing the tree using a recursive function to find both nodes and their levels (d1 and d2) from the root.
While traversing, if the current node matches either of the given nodes, store its level.
Recursively search in the left and right subtrees:
If both left and right calls return non-null, it means one node is found in each subtree, so the current node is the LCA.
At this point, calculate the distance using: dist = d1 + d2 - 2 * level_of_LCA
If both nodes are found during traversal, return the computed distance.
If only one node is found, then from the LCA, find the distance to the other node using the helper function findLevel().
If none of the nodes are found, return -1.
C++
#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intval){data=val;left=nullptr;right=nullptr;}};// Function to find the level of a nodeintfindLevel(Node*root,intk,intlevel){if(root==nullptr)return-1;if(root->data==k)returnlevel;// Recursively call function on left childintleftLevel=findLevel(root->left,k,level+1);// If node is found on left, return level// Else continue searching on the right childif(leftLevel!=-1){returnleftLevel;}else{returnfindLevel(root->right,k,level+1);}}// Function to find the lowest common ancestor// and calculate distance between two nodesNode*findLcaAndDistance(Node*root,inta,intb,int&d1,int&d2,int&dist,intlvl){if(root==nullptr)returnnullptr;if(root->data==a){// If first node found, store level and// return the noded1=lvl;returnroot;}if(root->data==b){// If second node found, store level and// return the noded2=lvl;returnroot;}// Recursively call function on left childNode*left=findLcaAndDistance(root->left,a,b,d1,d2,dist,lvl+1);// Recursively call function on right childNode*right=findLcaAndDistance(root->right,a,b,d1,d2,dist,lvl+1);if(left!=nullptr&&right!=nullptr){// If both nodes are found in different// subtrees, calculate the distancedist=d1+d2-2*lvl;}// Return node found or nullptr if not foundif(left!=nullptr){returnleft;}else{returnright;}}// Function to find distance between two nodesintfindDist(Node*root,inta,intb){intd1=-1,d2=-1,dist;// Find lowest common ancestor and calculate distanceNode*lca=findLcaAndDistance(root,a,b,d1,d2,dist,1);if(d1!=-1&&d2!=-1){// Return the distance if both // nodes are foundreturndist;}if(d1!=-1){// If only first node is found, find// distance to second nodedist=findLevel(lca,b,0);returndist;}if(d2!=-1){// If only second node is found, find// distance to first nodedist=findLevel(lca,a,0);returndist;}// Return -1 if both nodes not foundreturn-1;}intmain(){// Hardcoded binary tree// 1// / \ // 2 3// / \ / \ // 4 5 6 7Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->left=newNode(4);root->left->right=newNode(5);root->right->left=newNode(6);root->right->right=newNode(7);inta=4,b=7;cout<<findDist(root,a,b)<<endl;return0;}
C
#include<stdio.h>#include<stdlib.h>structNode{intdata;structNode*left,*right;};// Function to find the level of a nodeintfindLevel(structNode*root,intk,intlevel){if(root==NULL)return-1;if(root->data==k)returnlevel;// Recursively call function on left childintleftLevel=findLevel(root->left,k,level+1);// If node is found on left, return level// Else continue searching on the right childif(leftLevel!=-1){returnleftLevel;}else{returnfindLevel(root->right,k,level+1);}}// Function to find the lowest common ancestor// and calculate distance between two nodesstructNode*findLcaAndDistance(structNode*root,inta,intb,int*d1,int*d2,int*dist,intlvl){if(root==NULL)returnNULL;if(root->data==a){// If first node found, store level and// return the node*d1=lvl;returnroot;}if(root->data==b){// If second node found, store level and// return the node*d2=lvl;returnroot;}// Recursively call function on left childstructNode*left=findLcaAndDistance(root->left,a,b,d1,d2,dist,lvl+1);// Recursively call function on right childstructNode*right=findLcaAndDistance(root->right,a,b,d1,d2,dist,lvl+1);if(left!=NULL&&right!=NULL){// If both nodes are found in different// subtrees, calculate the distance*dist=*d1+*d2-2*lvl;}// Return node found or NULL if not foundif(left!=NULL){returnleft;}else{returnright;}}// Function to find distance between two nodesintfindDist(structNode*root,inta,intb){intd1=-1,d2=-1,dist;// Find lowest common ancestor and calculate distancestructNode*lca=findLcaAndDistance(root,a,b,&d1,&d2,&dist,1);if(d1!=-1&&d2!=-1){// Return the distance if both nodes // are foundreturndist;}if(d1!=-1){// If only first node is found, find// distance to second nodedist=findLevel(lca,b,0);returndist;}if(d2!=-1){// If only second node is found, find// distance to first nodedist=findLevel(lca,a,0);returndist;}// Return -1 if both nodes not foundreturn-1;}structNode*createNode(intvalue){structNode*node=(structNode*)malloc(sizeof(structNode));node->data=value;node->left=node->right=NULL;returnnode;}intmain(){// Hardcoded binary tree// 1// / \ // 2 3// / \ / \ // 4 5 6 7structNode*root=createNode(1);root->left=createNode(2);root->right=createNode(3);root->left->left=createNode(4);root->left->right=createNode(5);root->right->left=createNode(6);root->right->right=createNode(7);inta=4,b=7;printf("%d\n",findDist(root,a,b));return0;}
Java
classNode{publicintdata;publicNodeleft,right;Node(intval){data=val;left=null;right=null;}}classGfG{// Function to find the level of a nodestaticintfindLevel(Noderoot,intk,intlevel){if(root==null)return-1;if(root.data==k)returnlevel;// Recursively call function on left childintleftLevel=findLevel(root.left,k,level+1);// If node is found on left, return level// Else continue searching on the right childif(leftLevel!=-1){returnleftLevel;}else{returnfindLevel(root.right,k,level+1);}}// Function to find the lowest common ancestor // and calculate distance between two nodesstaticNodefindLcaAndDistance(Noderoot,inta,intb,int[]d1,int[]d2,int[]dist,intlvl){if(root==null)returnnull;if(root.data==a){// If first node found, store level and // return the noded1[0]=lvl;returnroot;}if(root.data==b){// If second node found, store level and // return the noded2[0]=lvl;returnroot;}// Recursively call function on left childNodeleft=findLcaAndDistance(root.left,a,b,d1,d2,dist,lvl+1);// Recursively call function on right childNoderight=findLcaAndDistance(root.right,a,b,d1,d2,dist,lvl+1);if(left!=null&&right!=null){// If both nodes are found in different // subtrees, calculate the distancedist[0]=d1[0]+d2[0]-2*lvl;}// Return node found or null if not foundif(left!=null){returnleft;}else{returnright;}}// Function to find distance between two nodesstaticintfindDist(Noderoot,inta,intb){int[]d1={-1},d2={-1},dist={0};// Find lowest common ancestor and calculate distanceNodelca=findLcaAndDistance(root,a,b,d1,d2,dist,1);if(d1[0]!=-1&&d2[0]!=-1){// Return the distance if both nodes are foundreturndist[0];}if(d1[0]!=-1){// If only first node is found, find // distance to second nodedist[0]=findLevel(lca,b,0);returndist[0];}if(d2[0]!=-1){// If only second node is found, find // distance to first nodedist[0]=findLevel(lca,a,0);returndist[0];}// Return -1 if both nodes not foundreturn-1;}publicstaticvoidmain(String[]args){// Hardcoded binary tree// 1// / \// 2 3// / \ / \// 4 5 6 7Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);root.right.right=newNode(7);inta=4,b=7;System.out.println(findDist(root,a,b));}}
Python
classNode:def__init__(self,val):self.data=valself.left=Noneself.right=None# Function to find the level of a nodedeffindLevel(root,k,level):ifrootisNone:return-1ifroot.data==k:returnlevel# Recursively call function on left childleftLevel=findLevel(root.left,k,level+1)# If node is found on left, return level# Else continue searching on the right childifleftLevel!=-1:returnleftLevelelse:returnfindLevel(root.right,k,level+1)# Function to find the lowest common ancestor # and calculate distance between two nodesdeffindLcaAndDistance(root,a,b,d1,d2,dist,lvl):ifrootisNone:returnNoneifroot.data==a:# If first node found, store level and # return the noded1[0]=lvlreturnrootifroot.data==b:# If second node found, store level and # return the noded2[0]=lvlreturnroot# Recursively call function on left childleft=findLcaAndDistance(root.left,a,b,d1,d2,dist,lvl+1)# Recursively call function on right childright=findLcaAndDistance(root.right,a,b,d1,d2,dist,lvl+1)ifleftisnotNoneandrightisnotNone:# If both nodes are found in different # subtrees, calculate the distancedist[0]=d1[0]+d2[0]-2*lvl# Return node found or None if not foundifleftisnotNone:returnleftelse:returnright# Function to find distance between two nodesdeffindDist(root,a,b):d1=[-1]d2=[-1]dist=[0]# Find lowest common ancestor and calculate distancelca=findLcaAndDistance(root,a,b,d1,d2,dist,1)ifd1[0]!=-1andd2[0]!=-1:# Return the distance if both nodes are foundreturndist[0]ifd1[0]!=-1:# If only first node is found, find # distance to second nodedist[0]=findLevel(lca,b,0)returndist[0]ifd2[0]!=-1:# If only second node is found, find # distance to first nodedist[0]=findLevel(lca,a,0)returndist[0]# Return -1 if both nodes not foundreturn-1if__name__=="__main__":# Hardcoded binary tree# 1# / \# 2 3# / \ / \# 4 5 6 7root=Node(1)root.left=Node(2)root.right=Node(3)root.left.left=Node(4)root.left.right=Node(5)root.right.left=Node(6)root.right.right=Node(7)a=4b=7print(findDist(root,a,b))
C#
usingSystem;classNode{publicintdata;publicNodeleft,right;publicNode(intval){data=val;left=null;right=null;}}classGfG{// Function to find the level of a nodestaticintFindLevel(Noderoot,intk,intlevel){if(root==null)return-1;if(root.data==k)returnlevel;// Recursively call function on left childintleftLevel=FindLevel(root.left,k,level+1);// If node is found on left, return level// Else continue searching on the right childif(leftLevel!=-1){returnleftLevel;}else{returnFindLevel(root.right,k,level+1);}}// Function to find the lowest common ancestor // and calculate distance between two nodesstaticNodeFindLcaAndDistance(Noderoot,inta,intb,refintd1,refintd2,refintdist,intlvl){if(root==null)returnnull;if(root.data==a){// If first node found, store level and // return the noded1=lvl;returnroot;}if(root.data==b){// If second node found, store level and // return the noded2=lvl;returnroot;}// Recursively call function on left childNodeleft=FindLcaAndDistance(root.left,a,b,refd1,refd2,refdist,lvl+1);// Recursively call function on right childNoderight=FindLcaAndDistance(root.right,a,b,refd1,refd2,refdist,lvl+1);if(left!=null&&right!=null){// If both nodes are found in different // subtrees, calculate the distancedist=d1+d2-2*lvl;}// Return node found or null if not foundif(left!=null){returnleft;}else{returnright;}}// Function to find distance between two nodesstaticintFindDist(Noderoot,inta,intb){intd1=-1,d2=-1,dist=0;// Find lowest common ancestor and calculate distanceNodelca=FindLcaAndDistance(root,a,b,refd1,refd2,refdist,1);if(d1!=-1&&d2!=-1){// Return the distance if both nodes // are foundreturndist;}if(d1!=-1){// If only first node is found, find // distance to second nodedist=FindLevel(lca,b,0);returndist;}if(d2!=-1){// If only second node is found, find // distance to first nodedist=FindLevel(lca,a,0);returndist;}// Return -1 if both nodes not foundreturn-1;}staticvoidMain(string[]args){// Hardcoded binary tree// 1// / \// 2 3// / \ / \// 4 5 6 7Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);root.right.right=newNode(7);inta=4,b=7;Console.WriteLine(FindDist(root,a,b));}}
JavaScript
classNode{constructor(val){this.data=val;this.left=null;this.right=null;}}// Function to find the level of a nodefunctionfindLevel(root,k,level){if(root===null)return-1;if(root.data===k)returnlevel;// Recursively call function on left childconstleftLevel=findLevel(root.left,k,level+1);// If node is found on left, return level// Else continue searching on the right childif(leftLevel!==-1){returnleftLevel;}else{returnfindLevel(root.right,k,level+1);}}// Function to find the lowest common ancestor // and calculate distance between two nodesfunctionfindLcaAndDistance(root,a,b,d1,d2,dist,lvl){if(root===null)returnnull;if(root.data===a){// If first node found, store level and // return the noded1[0]=lvl;returnroot;}if(root.data===b){// If second node found, store level and // return the noded2[0]=lvl;returnroot;}// Recursively call function on left childconstleft=findLcaAndDistance(root.left,a,b,d1,d2,dist,lvl+1);// Recursively call function on right childconstright=findLcaAndDistance(root.right,a,b,d1,d2,dist,lvl+1);if(left!==null&&right!==null){// If both nodes are found in different // subtrees, calculate the distancedist[0]=d1[0]+d2[0]-2*lvl;}// Return node found or null if not foundif(left!==null){returnleft;}else{returnright;}}// Function to find distance between two nodesfunctionfindDist(root,a,b){constd1=[-1];constd2=[-1];constdist=[0];// Find lowest common ancestor and calculate distanceconstlca=findLcaAndDistance(root,a,b,d1,d2,dist,1);if(d1[0]!==-1&&d2[0]!==-1){// Return the distance if both nodes are foundreturndist[0];}if(d1[0]!==-1){// If only first node is found, find // distance to second nodedist[0]=findLevel(lca,b,0);returndist[0];}if(d2[0]!==-1){// If only second node is found, find // distance to first nodedist[0]=findLevel(lca,a,0);returndist[0];}// Return -1 if both nodes not foundreturn-1;}// Hardcoded binary tree// 1// / \// 2 3// / \ / \// 4 5 6 7constroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);root.right.right=newNode(7);consta=4;constb=7;console.log(findDist(root,a,b));
Output
4
Using LCA (One Pass) - O(n) Time and O(h) Space
The idea is to find both target nodes in a single traversal of the tree while simultaneously calculating their distance. Instead of separately finding LCA and then distances, everything is handled in one DFS.
The function returns two things: Whether the current subtree contains either of the target nodes and distance from the current node to the found node.
Steps:
Start DFS traversal from the root.
Recursively check left and right subtrees.
At each node, check if it is equal to either target node.
If a node is found, start counting its distance upward.
If one target is found in the left subtree and the other in the right subtree, the current node is the LCA.
At LCA, the distance between both nodes is: left distance + right distance
While returning back, propagate whether a target node has been found and its distance.
Finally, the stored distance is returned as the answer.
C++
#include<bits/stdc++.h>usingnamespacestd;classNode{public:Node*left,*right;intdata;Node(intval){data=val;left=nullptr;right=nullptr;}};// Function that calculates distance between two nodes.// It returns a pair where the first element indicates // whether n1 or n2 is found and the second element // is the distance from the current node.pair<bool,int>calculateDistance(Node*root,intn1,intn2,int&distance){if(!root)return{false,0};// Recursively calculate the distance in// the left and right subtreespair<bool,int>left=calculateDistance(root->left,n1,n2,distance);pair<bool,int>right=calculateDistance(root->right,n1,n2,distance);// Check if the current node is either n1 or n2boolcurrent=(root->data==n1||root->data==n2);// If current node is one of n1 or n2 and // we found the other in a subtree, update distanceif(current&&(left.first||right.first)){distance=max(left.second,right.second);return{false,0};}// If left and right both returned true, // root is the LCA and we update the distanceif(left.first&&right.first){distance=left.second+right.second;return{false,0};}// If either left or right subtree contains n1 or n2, // return the updated distanceif(left.first||right.first||current){return{true,max(left.second,right.second)+1};}// If neither n1 nor n2 exist in the subtreereturn{false,0};}// The function that returns distance between n1 and n2.intfindDist(Node*root,intn1,intn2){intdistance=0;calculateDistance(root,n1,n2,distance);returndistance;}intmain(){// 1// / \ // 2 3// / \ / \ // 4 5 6 7Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->left=newNode(4);root->left->right=newNode(5);root->right->left=newNode(6);root->right->right=newNode(7);cout<<findDist(root,4,7);return0;}
C
#include<stdio.h>#include<stdlib.h>#include<stdbool.h>structNode{intdata;structNode*left;structNode*right;};// Function that calculates distance between two nodes.// It returns a pair where the first element indicates // whether n1 or n2 is found and the second element // is the distance from the current node.structPair{boolfound;intdistance;};structPaircalculateDistance(structNode*root,intn1,intn2,int*distance){if(!root)return(structPair){false,0};structPairleft=calculateDistance(root->left,n1,n2,distance);structPairright=calculateDistance(root->right,n1,n2,distance);boolcurrent=(root->data==n1||root->data==n2);if(current&&(left.found||right.found)){*distance=(left.distance>right.distance)?left.distance:right.distance;return(structPair){false,0};}if(left.found&&right.found){*distance=left.distance+right.distance;return(structPair){false,0};}if(left.found||right.found||current){return(structPair){true,(left.distance>right.distance?left.distance:right.distance)+1};}return(structPair){false,0};}// The function that returns distance between n1 and n2.intfindDist(structNode*root,intn1,intn2){intdistance=0;calculateDistance(root,n1,n2,&distance);returndistance;}structNode*createNode(intval){structNode*newNode=(structNode*)malloc(sizeof(structNode));newNode->data=val;newNode->left=NULL;newNode->right=NULL;returnnewNode;}intmain(){// 1// / \ // 2 3// / \ / \ // 4 5 6 7structNode*root=createNode(1);root->left=createNode(2);root->right=createNode(3);root->left->left=createNode(4);root->left->right=createNode(5);root->right->left=createNode(6);root->right->right=createNode(7);printf("%d",findDist(root,4,7));return0;}
Java
classNode{intdata;Nodeleft,right;Node(intval){data=val;left=null;right=null;}}classGfG{// Function that calculates distance between two nodes.// It returns an array where the first element indicates // whether n1 or n2 is found and the second element // is the distance from the current node.staticint[]calculateDistance(Noderoot,intn1,intn2,int[]distance){if(root==null)returnnewint[]{0,0};// Recursively calculate the distance in the// left and right subtreesint[]left=calculateDistance(root.left,n1,n2,distance);int[]right=calculateDistance(root.right,n1,n2,distance);// Check if the current node is either n1 or n2booleancurrent=(root.data==n1||root.data==n2);// If current node is one of n1 or n2 and we // found the other in a subtree, update distanceif(current&&(left[0]==1||right[0]==1)){distance[0]=Math.max(left[1],right[1]);returnnewint[]{0,0};}// If left and right both returned true, // root is the LCA and we update the distanceif(left[0]==1&&right[0]==1){distance[0]=left[1]+right[1];returnnewint[]{0,0};}// If either left or right subtree contains // n1 or n2, return the updated distanceif(left[0]==1||right[0]==1||current){returnnewint[]{1,Math.max(left[1],right[1])+1};}// If neither n1 nor n2 exist in the subtreereturnnewint[]{0,0};}// The function that returns distance between n1 and n2.staticintfindDist(Noderoot,intn1,intn2){int[]distance={0};calculateDistance(root,n1,n2,distance);returndistance[0];}publicstaticvoidmain(String[]args){// 1// / \// 2 3// / \ / \// 4 5 6 7Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);root.right.right=newNode(7);System.out.println(findDist(root,4,7));}}
Python
classNode:def__init__(self,val):self.data=valself.left=Noneself.right=None# Function that calculates distance between two nodes.# It returns a tuple where the first element indicates # whether n1 or n2 is found and the second element # is the distance from the current node.defcalculateDistance(root,n1,n2,distance):ifnotroot:return(False,0)left=calculateDistance(root.left,n1,n2,distance)right=calculateDistance(root.right,n1,n2,distance)current=(root.data==n1orroot.data==n2)ifcurrentand(left[0]orright[0]):distance[0]=max(left[1],right[1])return(False,0)ifleft[0]andright[0]:distance[0]=left[1]+right[1]return(False,0)ifleft[0]orright[0]orcurrent:return(True,max(left[1],right[1])+1)return(False,0)# The function that returns distance between n1 and n2.deffindDist(root,n1,n2):distance=[0]calculateDistance(root,n1,n2,distance)returndistance[0]if__name__=="__main__":# 1# / \# 2 3# / \ / \# 4 5 6 7root=Node(1)root.left=Node(2)root.right=Node(3)root.left.left=Node(4)root.left.right=Node(5)root.right.left=Node(6)root.right.right=Node(7)print(findDist(root,4,7))
C#
usingSystem;classNode{publicintdata;publicNodeleft,right;publicNode(intval){data=val;left=null;right=null;}}classGfG{// Function that calculates distance between two nodes.// It returns an array where the first element indicates // whether n1 or n2 is found and the second element // is the distance from the current node.staticint[]calculateDistance(Noderoot,intn1,intn2,refintdistance){if(root==null)returnnewint[]{0,0};// Recursively calculate the distance in the left// and right subtreesint[]left=calculateDistance(root.left,n1,n2,refdistance);int[]right=calculateDistance(root.right,n1,n2,refdistance);// Check if the current node is either n1 or n2boolcurrent=(root.data==n1||root.data==n2);// If current node is one of n1 or n2 and we // found the other in a subtree, update distanceif(current&&(left[0]==1||right[0]==1)){distance=Math.Max(left[1],right[1]);returnnewint[]{0,0};}// If left and right both returned true, // root is the LCA and we update the distanceif(left[0]==1&&right[0]==1){distance=left[1]+right[1];returnnewint[]{0,0};}// If either left or right subtree contains n1 or n2, // return the updated distanceif(left[0]==1||right[0]==1||current){returnnewint[]{1,Math.Max(left[1],right[1])+1};}// If neither n1 nor n2 exist in the subtreereturnnewint[]{0,0};}// The function that returns distance between n1 and n2.staticintfindDist(Noderoot,intn1,intn2){intdistance=0;calculateDistance(root,n1,n2,refdistance);returndistance;}staticvoidMain(){// 1// / \// 2 3// / \ / \// 4 5 6 7Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);root.right.right=newNode(7);Console.WriteLine(findDist(root,4,7));}}
JavaScript
classNode{constructor(val){this.data=val;this.left=null;this.right=null;}}// Function that calculates distance between two nodes.// It returns an object where the first property indicates // whether n1 or n2 is found and the second property // is the distance from the current node.functioncalculateDistance(root,n1,n2,distance){if(!root)return{found:false,dist:0};letleft=calculateDistance(root.left,n1,n2,distance);letright=calculateDistance(root.right,n1,n2,distance);letcurrent=(root.data===n1||root.data===n2);if(current&&(left.found||right.found)){distance.value=Math.max(left.dist,right.dist);return{found:false,dist:0};}if(left.found&&right.found){distance.value=left.dist+right.dist;return{found:false,dist:0};}if(left.found||right.found||current){return{found:true,dist:Math.max(left.dist,right.dist)+1};}return{found:false,dist:0};}// The function that returns distance// between n1 and n2.functionfindDist(root,n1,n2){letdistance={value:0};calculateDistance(root,n1,n2,distance);returndistance.value;}letroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);root.right.right=newNode(7);// 1// / \// 2 3// / \ / \// 4 5 6 7console.log(findDist(root,4,7));