I need some help for public class PostorderIterator implements Iterator public c
ID: 3754890 • Letter: I
Question
I need some help for public class PostorderIterator implements Iterator
public class BinaryTree {
//Implements a Binary Tree of Strings
private class Node {
private Node left;
private String data;
private Node right;
private Node parent; // reference to the parent node
// the parent is null for the root node
private Node(Node L, String d, Node r, Node p) {
left = L;
data = d;
right = r;
parent = p;
}
}
private Node root;
public BinaryTree() {
// create an empty tree
root = null;
}
public BinaryTree(String d) {
// create a tree with a single node
root = new Node(null, d, null, root);
}
public class PostorderIterator implements Iterator {
//An iterator that returns data in the tree in a post order pattern
//This implementation must use a stack and must not use the parent pointer
//You must use Java’s stack class
public PostorderIterator() {
}
public boolean hasNext() {
}
public String next() {
}
public void remove() {
//optional method not implemented
}
}
public Iterator postorder() {
// return a new post order iterator object
}
Explanation / Answer
I am writing Iterator in C# using stack
public class Post_Order_IteratorImpl : Post_Order_Iterator {
Stack<TreeNode> stack = new Stack<TreeNode>();
private void findNextLeaf(TreeNode cur) {
while ((cur != null)) {
this.stack.push(cur);
if ((cur.left != null)) {
cur = cur.left;
}
else {
cur = cur.right;
}
}
}
}
Unknown
[Override()]
public bool hasNext() {
return !stack.isEmpty();
}
[Override()]
public Integer next() {
if (!hasNext()) {
throw new NoSuchElementException("All have been visited!");
}
TreeNode res = stack.pop();
if (!stack.isEmpty()) {
TreeNode top = stack.peek();
if ((res == top.left)) {
findNextLeaf(top.right);
}
}
return res.val;
}
[Override()]
public void remove() {
throw new UnsupportedOperationException("remove() is not supported.");
}