Java 二叉树不插入到作为另一个节点左子节点的任何节点的右侧

Java 二叉树不插入到作为另一个节点左子节点的任何节点的右侧,java,binary-tree,binary-search-tree,Java,Binary Tree,Binary Search Tree,我的二叉树的当前插入方法不是插入到作为其父节点的左子节点的任何节点的右侧。 当前代码: private BinaryTreeNode insert(BinaryTreeNode current, String word) { if (current == null) { current = new BinaryTreeNode(word); } else { if (word.compareToIgnoreCase(current.value) &

我的二叉树的当前插入方法不是插入到作为其父节点的左子节点的任何节点的右侧。 当前代码:

private BinaryTreeNode insert(BinaryTreeNode current, String word) {
    if (current == null) {
        current = new BinaryTreeNode(word);
    } else {
        if (word.compareToIgnoreCase(current.value) < 0) { // if smaller than current node
            if (current.left != null) {
                if (word.compareToIgnoreCase(current.left.value) < 0) {// check next node for lesser than,
                    current.left = (insert(current.left, word));
                }
            } else {
                current.left = new BinaryTreeNode(word);// iff current node is end of tree
                System.out.println(word + "left");
            }
        } else {
            if (current.right != null) { // if larger than current node
                current.right = (insert(current.right, word));
            } else {
                current.right = new BinaryTreeNode(word); // if current node is end of tree
                System.out.println(word + "right");
            }
        }
    }
    return current;
}

你的问题在于:

if (word.compareToIgnoreCase(current.left.value) < 0) {// check next node for lesser than,
    current.left = (insert(current.left, word));
}

你希望这能做什么?您已经知道应该插入到当前节点的左侧,但为什么要在此处检查下一个节点?

您应该递归,而不是向下与左侧进行比较:

private static BinaryTreeNode insert(BinaryTreeNode current, String word) {
    if (current == null) {
        current = new BinaryTreeNode(word);
    } else {
        int test = word.compareToIgnoreCase(current.value);
        if (test < 0) {
            current.left = insert(current.left, word);
        } else if (test > 0) {
            current.right = insert(current.right, word);
        }
        // else word already at this node!
    }
    return current;
}

请注意,函数应该是静态的,因为它不依赖于此。

我认为有一些错误。。。我会这样做:

private void insert(BinaryTreeNode current, String word) {
    if (current == null) {
        current = new BinaryTreeNode(word);
    } else {
        if (word.compareToIgnoreCase(current.value) < 0) {

            if (current.left != null) {
                insert(current.left, word);
            } else {
                current.left = new BinaryTreeNode(word);
                System.out.println(word + "left");
            }

        } else {

            if (current.right != null) {
                insert(current.right, word);
            } else {
                current.right = new BinaryTreeNode(word); 
                System.out.println(word + "right");
            }

        }
    }
}

挑剔:OP应该使用递归,insert方法应该重复。我猜OP已经在这个项目上做了足够多的咒骂,他不需要再重复了。谢谢你指出这一点,我不知道为什么我会有这一行。我已经删除了它,现在正在等待测试用例完成运行。