如何在不影响原始树的情况下克隆整棵树?

时间:2011-10-18 07:51:11

标签: c#

我使用此链接中的解决方案无效 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;
        }

1 个答案:

答案 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;
}