2011-10-18 10 views
0

私は再帰的にすべてのノードを、 Deep cloning objects元のツリーに影響を与えずにツリー全体をクローンする方法は?

次のコードは動作しない新しいツリーにコピーすることはできません、変異し、このリンクでソリューションを使用し、元のツリーのルート(根)

    foreach (Bag b in bag_list) 
       { 
        if (b.cards.Count() == 2) 
        { 
         Node original_root = new Node(); 
         original_root = (Node)root.Clone(); // copy to a new tree 

         target_list = choose_valid_target(target_list, b.cards, b.cards.Count() - 1); 

         foreach (Target t in target_list) 
         { 
          Console.WriteLine("op:" + t.op + ", label:" + t.label); 

          Node mutated_root = mutate(original_root, target_list); 

          result = ""; 
          result = inorder(mutated_root, result); // get inorder 
          Console.WriteLine(result.Substring(1, result.Length - 2)); //print 
         } 
        } 
       } 

    public class Node : System.Object, ICloneable 
    { 
     public int priority; 
     /* 
     7 alphabet 
     6 (,) 
     5 *,/,% 
     4 +,- 
     3 <,<=,>,>= 
     2 &&,|| 
     1 = 
     */ 
     public string Data; 
     public Node Left; 
     public Node Right; 
     public string Label; 

     public object Clone() 
     { 
      //return this as object; 
      return this.MemberwiseClone(); 
      //return new Node() as object; 
     } 
    } 

     public Node mutate(Node root, List<Target> targets) // mutate 
     { 
      if (root != null) 
      { 
       if (!IsLeaf(root.Left.Data)) 
        mutate(root.Left, targets); 

       foreach (Target target in targets) 
       { 
        if (root.Label == target.label) 
        { 
         root.Data = target.op; 
        } 
       } 

       if (!IsLeaf(root.Right.Data)) 
        mutate(root.Right, targets); 
      } 
      return root; 
     } 

答えて

3

クローンに影響を与えます:

public object Clone() 
{ 
    Node clone = (Node)MemberwiseClone(); 
    if (Left != null) 
     clone.Left = (Node)Left.Clone(); 
    if (Right != null) 
     clone.Right = (Node)Right.Clone(); 
    return clone; 
} 
+0

clone.Left =(Node)Left.Clone(); –

関連する問題