Last active
July 19, 2017 03:40
-
-
Save anil477/c4eb6bd4f0454a0244bf35d25cc774f3 to your computer and use it in GitHub Desktop.
Largest and Second Largest In BST
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
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