Difference of Pairs on a BST Write a methodfunction that out
Difference of Pairs on a BST: Write a method/function that outputs two pointers pointing to two nodes, x and y, in a given BST, where the key values of x and y differ by a given integer k. Recall that we had given the following algorithm in lecture that on an sorted input array A and given value k returns two indices i and j, where A[i] – A[j] = k, or report error if such i and j do not exist:
i1; j2;
nlength[A] //assuming indices of A start with 1
while (jn and in)
d A[i] – A[j]
if (d==k)
return (i, j)
if (d<k)
i++
else
j++
return (-1, -1) //To indicate no such i and j exists.
Solution
int Diff(int[] a, int k)
{
int i=1; int j=2;
int n= a.length;
while(j<= n && i<=n){
d= a[i] - a[j];
}
if (d==k)
return (i,j);
if(d<k)
{
i++;
}
else {
j++;
return (-1,-1);
}
}
