Created
April 27, 2014 06:11
-
-
Save gabhi/11338746 to your computer and use it in GitHub Desktop.
Find LCA lowest common ancestor
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
public Node findLca(Node node, int t1, int t2) { | |
if(node == null) { | |
return null; | |
} | |
if(node.value > t2 && node.value > t1) { | |
// both targets are left | |
return findLca(node.left, t1, t2); | |
} else if (node.value < t2 && node.value < t1) { | |
// both targets are right | |
return findLca(node.right, t1, t2); | |
} else { | |
// either we are diverging or both targets are equal | |
// in both cases so we've found the LCA | |
// check for actual existence of targets here, if you like | |
return node; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment