Last active
May 16, 2017 10:19
-
-
Save lironsade/8f8271ecf40fcafff7c9e17cd3a483cc to your computer and use it in GitHub Desktop.
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 Iterator<Integer> iterator() { | |
return new BSTIterator(); | |
} | |
/* Package Private Methods */ | |
Node findSuccessor(Node node) { | |
if(node == null) { | |
return null; | |
} | |
if (node.getRight() != null ) { | |
Node pointer = node.getRight(); | |
return findMin(node); | |
} else{ | |
Node dad = node.getDad(); | |
while(dad != null && node == dad.getRight()) { | |
node = node.getDad(); | |
dad = dad.getDad(); | |
} | |
return dad; | |
} | |
} | |
Node findMin(Node node) { | |
if (node == null) | |
return null; | |
if (node.getLeft() == null) | |
return node; | |
return findMin(node.getLeft()); | |
} | |
class BSTIterator implements Iterator<Integer> { | |
Node pointer = findMin(root); | |
@Override | |
public boolean hasNext() { | |
return pointer != null; | |
} | |
@Override | |
public Integer next() { | |
if (pointer == null) | |
throw new NoSuchElementException(); | |
int toReturn = pointer.getData(); | |
pointer = findSuccessor(pointer); | |
return toReturn; | |
} | |
@Override | |
public void remove() { | |
throw new java.lang.UnsupportedOperationException("Not supported yet."); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment