java:实现二叉搜索树并覆盖iterable

时间:2014-05-17 05:23:14

标签: java iterator iterable

我希望能够为每个循环使用a但我最终会进入无限循环 我没有使用递归,调试器没有给我任何提示。如果是的话,我没有得到它。

这是我的测试员:

    Student stud1 = new Student("nic", "aichael", "1234", 75, 90);
    Student stud2 = new Student("nic", "bichael", "1234", 75, 90);
    Student stud3 = new Student("nic", "cichael", "1234", 75, 90);
    Student stud4 = new Student("nic", "dichael", "1234", 75, 90);
    AVLPersonTree tree = new AVLPersonTree();
    tree.add(stud1);
    tree.add(stud2);
    tree.add(stud3);
    tree.add(stud4);
    for(Node node: tree){
        node.toString();
     }

这是我的AVLPersonTree课程:

    public class AVLPersonTree implements Iterable<Node>{
private Node root;
private int size;

public AVLPersonTree(){
    super();
    root = null;
}

public void add(Person newPerson){
    Node newNode = new Node(newPerson);
    if(root == null){
        root = newNode;
    }else{
        root.addNode(newNode);
    }
    size++;
}

public int size(){
    return size;
}


@Override
public Iterator iterator() {
    Iterator<Node> iterate = new Iterator(){

        @Override
        public boolean hasNext() {
            if(root == null){
                return false;
            }
            if(root.getLeftNode() == null && root.getRightNode() == null){
                return false;
            }
            return true;
        }

        @Override
        public Node next() {
            if (!hasNext()) {
                throw new java.util.NoSuchElementException("no more elements");
            }
            return preorderNext();
            }

        @Override
        public void remove() {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

    };
    return iterate;
}

private Node preorderNext() {
    Stack<Node> visiting = new Stack<>();
if (visiting.empty()) { // at beginning of iterator
    visiting.push(root);
}
Node node = visiting.pop();
// need to visit the left subtree first, then the right
// since a stack is a LIFO, push the right subtree first, then
// the left.  Only push non-null trees
if (node.getRightNode() != null) {
    visiting.push(node.getRightNode());
}
if (node.getLeftNode() != null) {
    visiting.push(node.getLeftNode());
}
// may not have pushed anything.  If so, we are at the end
if (visiting.empty()) { // no more nodes to visit
    root = null;
}
return node;
}

}

1 个答案:

答案 0 :(得分:1)

您的&#34; preorderNext&#34;功能错了。

begening的5行将始终为您带来&#34; root&#34;在&#34;节点&#34;

Stack<Node> visiting = new Stack<>();
if (visiting.empty()) { // at beginning of iterator
visiting.push(root);
}
Node node = visiting.pop();

所以你永远不会真正迭代,节点将永远是&#34; root&#34;