【问题标题】:Java Binary Search Tree Recursive Copy TreeJava二叉搜索树递归复制树
【发布时间】:2011-07-19 08:30:19
【问题描述】:

我正在解决一个问题,该问题需要我递归地复制二叉搜索树并返回该树。我在二叉搜索树类中编码,所以它会复制它所调用的任何二叉搜索树。要求说私有方法必须具有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;
}

这里是 Entry 类,所以你知道我有什么可用的:

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

【问题讨论】:

  • n00b - 回复:您建议的编辑:您可以发布自己问题的答案,而不是编辑其他人的答案。

标签: java recursion copy binary-tree


【解决方案1】:
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&lt;E&gt;Entry&lt;E&gt; 有什么原因吗?树的一部分不也是树吗?

【讨论】:

  • 看起来你的代码可以工作,但它不是我的导师想要的。我只被允许编辑 rcopy() 方法。
  • @n00b:因此,为节点创建一个新条目,递归复制左右子树,并将它们添加到您的节点。原理相同,仅在 rcopy 方法内可行。
  • 当然我们可以为您提供您需要的解决方案,但是您将一无所获。尝试根据您的需要调整样本。如果你被卡住了,你仍然可以再问一次。也许你想看这篇文章:en.wikipedia.org/wiki/Tree_traversal
  • 我对你的实际任务感到好奇。为什么要复制树?除了向学生展示如何进行树遍历之外,我看不出复制搜索树的充分理由。我看不到你写的东西,但我上面的例子不会复制current.element,只是引用它。通常,这正是您想要做的。在 Java 中,默认情况下所有内容都是按引用的。只有原始类型(int、float、bool)按值复制。
【解决方案2】:

只是想我会分享我得到的解决方案。我的主要问题是没有对对象进行深层复制,所以它会引用该对象而不是创建一个新对象。

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

(successor 是一种方法,它返回它之前的对象的条目) 感谢大家对问题的帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-02
    • 2017-03-25
    • 2021-09-01
    • 2021-07-03
    • 2019-04-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多