我使用此链接中的解决方案无效 Deep cloning objects
以下代码,无法复制到新树,mutate会影响原始树根(root)
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;
}
答案 0 :(得分: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;
}