FatimahFatCakes
FatimahFatCakes

Reputation: 331

How to duplicate a LinkedBinaryTree java?

Im trying to implement a method called mirror() which reverses the tree but does not change the original tree. I have made a method which flips and changes the original tree, and i plan to duplicate the original tree, and flip the new tree. I am stuck on implementing the duplication of the original tree.

/** Returns a mirrored copy of the tree */
public LinkedBinaryTree<E> mirror() {
    LinkedBinaryTree<E> reversed = new LinkedBinaryTree<E>();

}

public void duplicate(Position<E> p) {

}

/** Reverses the tree */
public void reverseMe() {
    if (this.root != null) {
        reverseHelper(this.root);
    }
}

private void reverseHelper(Position<E> p) {
    Node<E> node = (Node<E>)p;

    if (node.getLeft() != null) {
        Node<E> temp = node.getLeft();
        node.setLeft(node.getRight());
        node.setRight(temp);

    } else if (node.getRight() != null) {
        Node<E> temp = node.getLeft();
        node.setLeft(node.getRight());
        node.setRight(temp);
    }

    if (node.getLeft() != null) {
        reverseHelper(node.getLeft());
    }

    if (node.getRight() != null) {
        reverseHelper(node.getRight());
    }           
}

Upvotes: 1

Views: 101

Answers (1)

Assafs
Assafs

Reputation: 3275

Perhaps something like this will help:

private Position<E> duplicate (Position<E> p) {
    Node<E> node = (Node<E>)p;
    Node<E> newNode = new Node<E>();

    //Set the contents of the node as needed.

    if (node.getLeft() != null) {
        newNode.setLeft(duplicate(node.getLeft());
    } 
    if (node.getRight() != null) {
        newNode.setRight(duplicate(node.getRight());
    }
    return newNode;
}

Please take into account that the content of any node needs to be copied where the comment suggests, and that I created a new instance of the Node in the most basic way - if there's a special constructor, please use it.

Upvotes: 2

Related Questions