在java中,如何在二进制搜索树的根位置插入项?

在java中,如何在二进制搜索树的根位置插入项?,java,binary-search-tree,Java,Binary Search Tree,我想在二叉搜索树的根中插入一个新项。下面,我将介绍此方法以及左右旋转的帮助方法。我认为(使用下面的方法)尝试按顺序遍历打印树时会出现错误,它会在新根后面停止,因此不会打印新根和根右侧的项目。在以正常方式将项目插入到树中后,我检查了打印方法,它正常工作,因此我认为没有问题 public class ST { private TreeNode root; public ST() { this.size = 0; this.root = null;

我想在二叉搜索树的根中插入一个新项。下面,我将介绍此方法以及左右旋转的帮助方法。我认为(使用下面的方法)尝试按顺序遍历打印树时会出现错误,它会在新根后面停止,因此不会打印新根和根右侧的项目。在以正常方式将项目插入到树中后,我检查了打印方法,它正常工作,因此我认为没有问题

public class ST {

    private TreeNode root;

    public ST() {
        this.size = 0;
        this.root = null;
    }

    public void insert_at_root(Suspect item) {
        insert_at_rootRec(item, this.root);
    }

    private TreeNode insert_at_rootRec(Suspect item, TreeNode head) {
        if (head == null)
            return new TreeNode(item);
        if (item.key() < head.item.key()) {
            head.left = insert_at_rootRec(item, head.left);
            head = rotateRight(head);
        } else {
            head.right = insert_at_rootRec(item, head.right);
            head = rotateLeft(head);
        }
        return head;

    }

    private TreeNode rotateRight(TreeNode h) {
        TreeNode x = h.left;
        h.left = x.right;
        x.right = h;
        return x;
    }

    private TreeNode rotateLeft(TreeNode h) {
        TreeNode x = h.right;
        h.right = x.left;
        x.left = h;
        return x;
    }



    public void printTreeByAFM(PrintStream stream) {
        printTreeByAFMRec(this.root, stream);
    }

    private void printTreeByAFMRec(TreeNode root, PrintStream stream) {
        if (root == null)
            return;
        printTreeByAFMRec(root.left, stream);
        stream.println(root.item);
        printTreeByAFMRec(root.right, stream);
    }

}
公共类ST{
独活根;
公共服务{
此值为0.size=0;
this.root=null;
}
在根目录处插入公共无效项(可疑项){
在_rootRec(项目,this.root)中插入_;
}
在rootRec处插入专用TreeNode(可疑项目,TreeNode头部){
if(head==null)
返回新的TreeNode(项目);
if(item.key()
您应该将计算的新树保存在
的根目录下插入

public void insert_at_root(Suspect item) {
    root = insert_at_rootRec(item, this.root);
}

对于
insert\u at\u rootRec()
的返回,您没有做任何事情,因此在计算新树之后,它只会进入垃圾收集器。

我没有看到任何设置
root
超出构造函数的内容。@John Sensebe这是一个递归方法,所以最后一次返回将是根。我不这么认为。要设置
root
,必须为
root
分配一些内容。这正是我应该回答的,但我担心这不是全部问题+1.