3

I have n-ry tree with node like this:

class Node
{
  public Node Parent = null;
  public List<Node> Children = new List<Node>();
  public string Name;
}

I need to do a deep copy of original tree and avoid changing of new tree when original tree is changed. I know only how to do shallow copy:

public Node Copy(Node original)
{
  Node newNode = new Node();
  newNode.Parent = original.Parent;
  newNode.Children = original.Children;
  newNode.Name = original.Name;

  return newNode;
}

In this case I copy both Nodes point to on object in memory and when original node changed a newNode will be changed to. Could anyone help me to do deep cloning?

icedwater
  • 4,701
  • 3
  • 35
  • 50

2 Answers2

1

You've to do it recursively. And you need a parent for the created clone.

public Node Copy(Node origin, Node parent = null)
{
    if (origin == null)
    {
        return null;
    }

    var result = new Node { Parent = parent, Name = origin.Name };
    result.Children = origin.Children != null ? origin.Children.Select(x => Copy(x, result)).ToList() : null;
    return result;
}

This will help if you only have Node and no system types.

Sebastian Schumann
  • 3,204
  • 19
  • 37
0

Do it recursivly. Note that this will set the parent of the first node to null. I.e. if you start copying from the middle of the tree, the parent node will not be maintained.

public Node Copy()
{
  Node newNode = new Node();
  newNode.Name = this.Name;

  foreach(var child in this.Children)
  {
      newChild = child.Copy();
      newChild.Parent = newNode;
      newNode.Children.Add(newChild);
  }

  return newNode;
}
Lorentz Vedeler
  • 5,101
  • 2
  • 29
  • 40