Created
July 19, 2017 03:40
-
-
Save anil477/5f295f563c5be7eb55d6300d01dfec08 to your computer and use it in GitHub Desktop.
Find Second Largest - Iterative
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) { | |
BinaryTreeNode current = rootNode; | |
while (current.right != null) { | |
current = current.right; | |
} | |
return current.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"); | |
} | |
BinaryTreeNode current = rootNode; | |
while (true) { | |
// case: current is largest and has a left subtree | |
// 2nd largest is the largest in that subtree | |
if (current.left != null && current.right == null) { | |
return findLargest(current.left); | |
} | |
// case: current is parent of largest, and largest has no children, | |
// so current is 2nd largest | |
if (current.right != null && | |
current.right.left == null && | |
current.right.right == null) { | |
return current.value; | |
} | |
current = current.right; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment