Make delicious recipes!

Clone graph recursively



Puzzle: Given a graph (where each node has a variable number of children), write a function to recursively clone it.

Code:


Node clone (Node orig)
{
    Node c = new Node ();
    clone (orig, c);
    return c;
}



void clone(Node orig, Node c) 
{
    c.data = orig.data;
    c.children = new ArrayList <Node> (orig.children.size());

    for (int i=0; i<orig.children.size(); i++)
        c.children.add(clone(orig.children.get(i)));
}









Like us on Facebook to remain in touch
with the latest in technology and tutorials!


Got a thought to share or found a
bug in the code?
We'd love to hear from you:

Name:
Email: (Your email is not shared with anybody)
Comment:

Facebook comments:

Site Owner: Sachin Goyal