Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Deep cloning a Binary Tree

807588Jul 12 2009 — edited Jul 17 2009
Hi, I have a class called DigitalTree that acts like a binary tree, storing nodes that each have a "key" which is a long value, and then puts each node into the tree in its correct place, binary tree style. I am trying to deep clone the tree, but for some reason my recursive cloning method isn't working. If anyone can see a problem in my code or has any tips for me, it would be greatly appreciated. Thanks.
public Object clone()
   {
       DigitalTree<E> treeClone = null;
       try
       {
           treeClone = (DigitalTree<E>)super.clone();
       }
       catch(CloneNotSupportedException e)
       {
           throw new Error(e.toString());
       }

       cloneNodes(treeClone, this.root, treeClone.root);
       return treeClone;
   }

   private void cloneNodes(DigitalTree treeClone, Node currentNode, Node cloneNode)
   {
       if(treeClone.size == 0)
       {
           cloneNode = null;
           cloneNodes(treeClone, currentNode.left, cloneNode.left);
           cloneNodes(treeClone, currentNode.right, cloneNode.right);
       }
       else if(currentNode != null)
       {
           cloneNode = (Node<E>)currentNode.clone();
           cloneNodes(treeClone, currentNode.left, cloneNode.left);
           cloneNodes(treeClone, currentNode.right, cloneNode.right);
       }
   }
In the Node class:
public Object clone()
      {
          Node<E> nodeClone = null;
          try
          {
               nodeClone = (Node<E>)super.clone();
          }
          catch(CloneNotSupportedException e)
          {
               throw new Error(e.toString());
          }

          return nodeClone;
       }
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Aug 14 2009
Added on Jul 12 2009
6 comments
1,295 views