[英]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.