Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deep copy a Binary Tree?

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!

like image 554
lkkeepmoving Avatar asked Apr 19 '13 06:04

lkkeepmoving


People also ask

How do you recursively copy a binary tree?

The idea very simple – recursively traverse the binary tree in a preorder fashion, and for each encountered node, create a new node with the same data and insert a mapping from the original tree node to the new node in a hash table. After creating the mapping, recursively process its children.

How deep is a binary tree?

The depth of a node in a binary tree is the total number of edges from the root node to the target node. Similarly, the depth of a binary tree is the total number of edges from the root node to the most distant leaf node.

What is cloning a binary tree?

You are given a binary tree. Apart from the left and right child pointers, each node in the given binary tree points to a random node in the given binary tree. You are supposed to return a clone of the binary tree. Cloning a binary tree means making a deep copy of the input binary tree.

What is cloned tree?

Should a tree become severely damaged or killed, thousands of shoots can develop from the expanse of the parent trees root distribution. As they mature these individually identical groups of new growth are referred to as clone clumps.


2 Answers

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);
    }
}
like image 187
Evgeniy Dorofeev Avatar answered Oct 19 '22 03:10

Evgeniy Dorofeev


Doing it recursively using pre-order traversal.

    public static Node CopyTheTree(Node root)
    {
        if (root == null)
        {
            return null;
        }
        Node newNode = new Node(null, null, root.Value);
        newNode.Left= CopyTheTree(root.Left);
        newNode.Right= CopyTheTree(root.Right);
        return newNode;
    }
like image 36
aerin Avatar answered Oct 19 '22 02:10

aerin