通过二进制搜索树java迭代

时间:2016-12-15 13:37:31

标签: java loops binary-search-tree

有人可以告诉我循环二叉树以遍历所有节点的方法。 我将通过插入方法添加学生。 我只想打印所有学生的对象。 这是我的BST:

public class BinarySearchTree<Students extends Comparable<? super Student>> {
    public static BinaryNode root;

    public BinarySearchTree() {
        this.root = null;
    }

public void insert(Student student) {

        root = insert(student, root);
    }

    protected BinaryNode<Student> insert(Student student, BinaryNode<Student> t) {
        if (t == null) {

            t = new BinaryNode<Student>(student);
        } else if (student.compareTo(t.element) < 0) {
            t.left = insert(student, t.left);
        } else if (student.compareTo(t.element) > 0) {
            t.right = insert(student, t.right);
        } else {
            // throw new DuplicateItemException(student.toString());
        }
        return t;
    }
}

节点类:

class BinaryNode<Student> {
    // Constructor
    BinaryNode(Student theElement) {
        element = theElement;
        left = right = null;
    }

    // Data; accessible by other package routines
    Student element; // The data in the node
    BinaryNode<Student> left; // Left child
    BinaryNode<Student> right; // Right child
}

3 个答案:

答案 0 :(得分:0)

将此方法添加到BinarySearchTree类:

public void inorder(BinaryNode node) {
    if (node == null) {
        return;
    }
    inorder(node.left);
    System.out.print(...); //whatever you want to do with the node
    inorder(node.right);
}

以类似的方式,您可以执行预订延期交付遍历。

答案 1 :(得分:0)

public class BinarySearchTree<Students extends Comparable<? super Student>> {
    public static BinaryNode root;

    public BinarySearchTree() {
        this.root = null;
    }
    ...
    public void print() {
        print(root);
    }

    public void print(BinaryNode<Student> node) {
        if (node == null) {
            return;
        }
        print(node.left);
        doSomething(node.getStudent());
        print(node.right);
    }
}

答案 2 :(得分:0)

有三种方法可以遍历二叉搜索树。

  • <强>预购

    public void preOrder(BinaryNode node) {
        if (node == null) {
            return;
        }
        doSomethig(node.element); // process node
        preOrder(node.left);
        preOrder(node.right);
    }
    
  • 有序在这种情况下,节点按顺序遍历

    public void inOrder(BinaryNode node) {
        if (node == null) {
            return;
        }
        inOrder(node.left);
        doSomethig(node.element); // process node
        inOrder(node.right);
    }
    
  • 发表阶

    public void postOrder(BinaryNode node) {
        if (node == null) {
            return;
        }
        postOrder(node.left);
        postOrder(node.right);
        doSomethig(node.element); // process node
    }
    

你必须选择其中一个并运行例如:

    preOrder(root); // where root is a handle to your BST