Skip to content

Instantly share code, notes, and snippets.

@anil477
Created 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/5f295f563c5be7eb55d6300d01dfec08 to your computer and use it in GitHub Desktop.
Save anil477/5f295f563c5be7eb55d6300d01dfec08 to your computer and use it in GitHub Desktop.
Find Second Largest - Iterative
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