Java 二叉搜索树 递归复制树
我正在解决一个问题,需要我递归地复制二叉搜索树并返回该树。我正在二叉搜索树类中进行编码,因此它将复制它所调用的任何二叉搜索树。要求规定私有方法必须具有 Entry
返回类型和 Entry
类型的参数。我遇到的问题是将多个条目添加到树中。
这是我目前拥有的:
public BinarySearchTree<E> rcopy(){
BinarySearchTree newTree = new BinarySearchTree();
newTree.add(rcopy(root).element);
return newTree;
}
private Entry <E> rcopy(Entry <E> current){
if(current.left!=null) return rcopy(current.left);
if(current.right!=null) return rcopy(current.right);
return current;
}
这是入门课程,因此您知道我可以使用什么:
protected static class Entry<E> {
protected E element;
protected Entry<E> left = null,
right = null,
parent;
protected int pos;
protected Entry<E> link = null;
public Entry() { }
public Entry (E element, Entry<E> parent)
{
this.element = element;
this.parent = parent;
}
}
I'm working on a problem which requires me to copy a binary search tree recursively and to return the tree. I am coding in the binary search tree class, so it will copy whatever binary search tree it is called on. The requirements say that the private method must have a return type of Entry<E>
and a parameter of type Entry<E>
. The problem I'm running into is getting multiple entries added to the tree.
Here is what I currently have:
public BinarySearchTree<E> rcopy(){
BinarySearchTree newTree = new BinarySearchTree();
newTree.add(rcopy(root).element);
return newTree;
}
private Entry <E> rcopy(Entry <E> current){
if(current.left!=null) return rcopy(current.left);
if(current.right!=null) return rcopy(current.right);
return current;
}
And here is Entry class so you know what I have available to me:
protected static class Entry<E> {
protected E element;
protected Entry<E> left = null,
right = null,
parent;
protected int pos;
protected Entry<E> link = null;
public Entry() { }
public Entry (E element, Entry<E> parent)
{
this.element = element;
this.parent = parent;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这不会复制任何内容。它将返回当前节点的最左边(或最右边,如果没有左子节点;或当前,如果它是叶节点)子节点。因为你总是返回电流。您需要类似的东西:
并实际复制节点。我还没有测试代码,现在有点晚了,希望它仍然是正确的。
您区分
BinarySearchTree
和Entry
是否有原因?树的一部分不也是树吗?This will not copy anything. It will return the left-most ( or right-most, if no left child; or current, if it is a leaf node ) child of the current node. Because you always return current. You need somelthing like:
and actually copy the nodes. I haven't tested the code and it is bit late, hope it is still correct.
Is there a reason you distinguish between
BinarySearchTree<E>
andEntry<E>
? Isn't a part of the tree also a tree?只是想我会分享我得到的解决方案。我的主要问题是没有对对象进行深层复制,因此它会引用该对象而不是创建一个新对象。
(后继者是一种返回其前面的对象条目的方法)
感谢大家帮助解决问题!
Just thought I would share the solution that I got. My main problem was not doing a deep copy on the object so, it would reference the object instead of creating a new one.
(successor is a method that returns an entry of the object that preceeds it)
Thank you every one for help with the problem!