Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/svn/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 通过插入合并2个二进制搜索树_Java_Insert_Merge_Binary Search Tree - Fatal编程技术网

Java 通过插入合并2个二进制搜索树

Java 通过插入合并2个二进制搜索树,java,insert,merge,binary-search-tree,Java,Insert,Merge,Binary Search Tree,我目前正在实现一个二叉搜索树,并且在将它与另一个二叉搜索树合并时遇到了困难。 到目前为止,我已经: head:返回具有最小节点的节点 tail:返回没有最小节点的树 insertvalue:传统的插入方法 因为我得到了一个StackOverflower错误,我认为最好提供所有的方法,而不仅仅是合并方法。我很确定这个错误是由于递归调用的数量造成的 我将感谢任何帮助!TYVM public BinaryTree insert(int newValue) { if (newValue <

我目前正在实现一个二叉搜索树,并且在将它与另一个二叉搜索树合并时遇到了困难。 到目前为止,我已经:

head:返回具有最小节点的节点 tail:返回没有最小节点的树 insertvalue:传统的插入方法 因为我得到了一个StackOverflower错误,我认为最好提供所有的方法,而不仅仅是合并方法。我很确定这个错误是由于递归调用的数量造成的

我将感谢任何帮助!TYVM

public BinaryTree insert(int newValue) {
    if (newValue < value) {
        if (left == null) {
            return new BinaryTree(value, new BinaryTree(newValue), right);
        } else {
            return new BinaryTree(value, left.insert(newValue), right);
        }
    } else if (newValue > value) {
        if (right == null) {
            return new BinaryTree(value, left, new BinaryTree(newValue));
        } else {
            return new BinaryTree(value, left, right.insert(newValue));
        }
    }
    return this;
}

public int head() {
    if (left != null) {
        return left.head();
    }
    return value;
}

public BinaryTree tail() {
    if (left != null) {
        return new BinaryTree(value, left.tail(), right);
    } else {
        return new BinaryTree(value, left, right.tail());
    }

嘿,谢谢你的回复。不过它还是给了我StackOverflower的错误。我认为问题在于尾巴。如果我能在不使用头部的情况下让尾巴工作,它可能会工作-我添加了逻辑尾部实现。最后一个实现的方法总是会被搞得一团糟。
public BinaryTree merge(BinaryTree other) {
    if (other != null) {
        insert(other.head()merge(other.tail()));
    }
    return this;
}
public BinaryTree merge(BinaryTree other) {
    if (other != null) {
        return insert(other.head()).merge(other.tail());
    }
    return this;
}
/**
 * Get the tail of a tree.
 * @return the tree without the smallest value.
 */
public BinaryTree tail() {
    if (left != null) {
        return new BinaryTree(value, left.tail(), right);
    }
    return right; // Could make a deep copy.
}