如何在C#中将一棵树插入另一棵树

How to insert a tree into another tree in C#

我有两棵这样的树:

我想将第二棵树插入第一棵树中的一个节点,该节点与其根节点同名,并将该节点的子节点附加到第二棵树的最左边的子节点。

我试过了:

    PTree attachPoint = chain.Find(x => x.Val == RTree.Val);


    if (attachPoint != null)
    {
        foreach (var c in attachPoint.Childs)
        {
            RTree.Left.Childs.Add(c);
        }
        attachPoint = RTree;
    }
    else
    {
        RTree.Left.Childs.Add(root);
        root = RTree;
    }

这里,RTree是第二棵树,root指向第一棵树的根,chain持有从根"A"到[=24=的分支].但似乎没有构建所需的树。我做对了吗?

attachPoint(和root?)只是局部变量所以attachPoint = RTree;不会影响树的结构。需要搜索左树找到插入点的父节点,然后修改父节点使得parent.Right = attachPoint;

如果您已经包含 PTree class 的基本部分,那么帮助会更容易。以下是我可以根据发布的代码向您提出的建议:

PTree attachPoint = chain.Find(x => x.Val == RTree.Val);

if (attachPoint != null)
{
    foreach (var c in attachPoint.Childs)
    {
        RTree.Left.Childs.Add(c);
    }
    // Here you either have to find the attachPoint parent and
    // replace attachPoint with RTree in parent.Childs,
    // or make attachPoint.Childs to be RTree.Childs as below
    attachPoint.Childs.Clear();
    foreach (var c in RTree.Childs)
    {
        attachPoint.Childs.Add(c);
    }
}
else
{
    RTree.Left.Childs.Add(root);
    root = RTree;
}