How to deep copy a Binary Tree?

lkkeepmoving picture lkkeepmoving · Apr 19, 2013 · Viewed 33.4k times · Source

I would like using my own Node class to implement tree structure in Java. But I'm confused how to do a deep copy to copy a tree.

My Node class would be like this:

public class Node{
private String value;
private Node leftChild;
private Node rightChild;
....

I'm new to recursion, so is there any code I can study? Thank you!

Answer

Evgeniy Dorofeev picture Evgeniy Dorofeev · Apr 19, 2013

try

class Node {
    private String value;
    private Node left;
    private Node right;

    public Node(String value, Node left, Node right) {
        this.value = value;
        ...
    }

    Node copy() {
        Node left = null;
        Node right = null;
        if (this.left != null) {
            left = this.left.copy();
        }
        if (this.right != null) {
            right = this.right.copy();
        }
        return new Node(value, left, right);
    }
}