【问题标题】:How to insert a tree into another tree in C#如何在 C# 中将一棵树插入另一棵树
【发布时间】:2016-05-19 16:27:53
【问题描述】:

我有两棵这样的树:

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

我试过了:

    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”到“D”的分支。但似乎没有建立所需的树。我做对了吗?

【问题讨论】:

  • 一个节点的最大子节点数是多少?这看起来不像二叉树,但一个节点包含一个Left-child-node。看起来很奇怪。
  • @Verarind 你可以假设RTree,第二个孩子,是二元的,Left 实际上是 childs[1] 而Rightchilds[0]

标签: c# algorithm tree


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-09
      • 2010-10-21
      • 2015-12-20
      相关资源
      最近更新 更多