繁体   English   中英

Java二进制搜索树递归副本树

[英]Java Binary Search Tree Recursive Copy Tree

我正在解决一个问题,该问题要求我递归复制二进制搜索树并返回该树。 我在二进制搜索树类中进行编码,因此它将复制它被调用的任何二进制搜索树。 要求说,私有方法必须返回类型Entry<E>和类型的参数Entry<E> 我遇到的问题是将多个条目添加到树中。

这是我目前拥有的:

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;
    }
}
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;
}

这不会复制任何内容。 它将返回当前节点的最左侧(如果没有左侧子节点,则返回最右;如果是叶节点,则返回当前节点)。 因为您总是返回电流。 您需要类似的东西:

private Entry <E> rcopy(Entry <E> current){
    if (current == null) return null;
    return new Entry <E> (current.element, rcopy(current.left), rcopy(current.right)); //write a constructor for that
 }

并实际复制节点。 我尚未测试代码,但为时已晚,希望它仍然正确。

您是否有理由区分BinarySearchTree<E>Entry<E> 树的一部分不是树吗?

只是以为我会分享我得到的解决方案。 我的主要问题不是在对象上进行深复制,因此它将引用该对象而不是创建一个新对象。

public BinarySearchTree<E> rcopy(){
   BinarySearchTree<E> newTree = new BinarySearchTree<E>();
   newTree.root = rcopy(root);
   newTree.size=newTree.nodes();
   return newTree;
}
private Entry <E> rcopy(Entry <E> current){
   Entry <E> b=new Entry<E>();
   if(current!=null){
      if(current.left!=null)b.left=rcopy(current.left);
      if(current.right!=null)b.right=rcopy(current.right);
      b.element = current.element;
      b.parent = successor(current);
   }
   return b;
}

(后继方法是一种返回该对象之前的对象的条目的方法) 谢谢大家对问题的帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM