Created
March 5, 2018 03:52
-
-
Save rootChuTney-RaviBhanot/b8547ec2bae65b2a13635e265ec91eaf to your computer and use it in GitHub Desktop.
Given the insertion order of nodes in a binary search tree, find the distance between two nodes in the tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
public class DistanceBetweenTwoNodesWithUnbuiltTree { | |
/* | |
* Distance between two nodes is number of edges between the two nodes | |
*/ | |
public static int distanceBetweenTwoNodesofBstWithUnbuiltTree(int[] insertionOrder, int node1, int node2) { | |
if (insertionOrder == null || insertionOrder.length == 0) { | |
return -1; | |
} | |
List<Integer> node1Path = rootToNodeHelper(insertionOrder, node1); | |
List<Integer> node2Path = rootToNodeHelper(insertionOrder, node2); | |
if (node1Path == null || node2Path == null) { | |
return -1; | |
} | |
int node1Runner = 0; | |
int node2Runner = 0; | |
int node1PathLength = node1Path.size(); | |
int node2PathLength = node2Path.size(); | |
while(node1Runner < node1PathLength && node2Runner < node2PathLength && node1Path.get(node1Runner) == node2Path.get(node2Runner)) { | |
node1Runner++; | |
node2Runner++; | |
} | |
if (node1Runner == node1PathLength && node2Runner == node2PathLength) { | |
// Same nodes | |
return 0; | |
} else if (node1Runner == node1PathLength) { | |
return node2PathLength - node2Runner; | |
} else if (node2Runner == node2PathLength) { | |
return node1PathLength - node1Runner; | |
} else { | |
return (node1PathLength - node1Runner) + (node2PathLength - node2Runner); | |
} | |
} | |
private static List<Integer> rootToNodeHelper(int[] insertionOrder, int node) { | |
int rangeMin = Integer.MIN_VALUE; | |
int rangeMax = Integer.MAX_VALUE; | |
List<Integer> nodePath = new ArrayList<Integer>(); | |
for (int i = 0; i < insertionOrder.length; i++) { | |
int current = insertionOrder[i]; | |
if (current < rangeMin || current > rangeMax) { | |
continue; | |
} | |
if (current > node && current < rangeMax) { | |
rangeMax = current; | |
nodePath.add(current); | |
} else if (current < node && current > rangeMin) { | |
rangeMin = current; | |
nodePath.add(current); | |
} else if (current == node) { | |
nodePath.add(current); | |
break; | |
} | |
} | |
return (nodePath.get(nodePath.size()-1) == node) ? nodePath : null; | |
} | |
public static void main(String[] args) { | |
int[] insertionOrder = {9,1,5,7,8,10,12,4,6}; | |
System.out.println(distanceBetweenTwoNodesofBstWithUnbuiltTree(insertionOrder, 4, 6)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment