Interview Question
Country: United States
Solution does an initial inorder traversal of the tree and populating the queue with the nodes inorder.
class Node{
public int data;
public Node left;
public Node right;
}
public class InorderTreeIterator implements Iterator {
LinkedList<Node> nodeQueue;
Node currentNode;
public InorderTreeIterator(Node root){
nodeQueue = new LinkedList<Node>
initializeQueue(root);
}
public boolean hasNext(){
return(!nodeQueue.empty());
}
public Node next(){
if(hasNext())
return(nodeQueue.removeFirst());
return(null);
}
private initializeQueue(Node root){
if(root = null)
return;
initializeQueue(root.left);
nodeQueue.addLast(root);
initializeQueue(root.right);
}
}
If there is a parent pointer, we can write a method which finds the successor of a given node.
So C# code might be something like this
- Loler October 08, 2012