Skip to content

Instantly share code, notes, and snippets.

@anil477
Last active July 19, 2017 03:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anil477/c4eb6bd4f0454a0244bf35d25cc774f3 to your computer and use it in GitHub Desktop.
Save anil477/c4eb6bd4f0454a0244bf35d25cc774f3 to your computer and use it in GitHub Desktop.
Largest and Second Largest In BST
private static int findLargest(BinaryTreeNode rootNode) {
if (rootNode == null) {
throw new IllegalArgumentException("Tree must have at least 1 node");
}
if (rootNode.right != null) {
return findLargest(rootNode.right);
}
return rootNode.value;
}
public static int findSecondLargest(BinaryTreeNode rootNode) {
if (rootNode == null || (rootNode.left == null
&& rootNode.right == null)) {
throw new IllegalArgumentException("Tree must have at least 2 nodes");
}
// case: we're currently at largest, and largest has a left subtree,
// so 2nd largest is largest in said subtree
if (rootNode.left != null && rootNode.right == null) {
return findLargest(rootNode.left);
}
// case: we're at parent of largest, and largest has no left subtree,
// so 2nd largest must be current node
if (rootNode.right != null
&& rootNode.right.left == null
&& rootNode.right.right == null) {
return rootNode.value;
}
// otherwise: step right
return findSecondLargest(rootNode.right);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment