C# 在C中如何将一棵树插入另一棵树#
我有两棵这样的树: 我想将第二棵树插入与根同名的节点中的第一棵树,并将此节点的子节点附加到第二棵树最左边的子节点 我试过:C# 在C中如何将一棵树插入另一棵树#,c#,algorithm,tree,C#,Algorithm,Tree,我有两棵这样的树: 我想将第二棵树插入与根同名的节点中的第一棵树,并将此节点的子节点附加到第二棵树最左边的子节点 我试过: PTree attachPoint = chain.Find(x => x.Val == RTree.Val); if (attachPoint != null) { foreach (var c in attachPoint.Childs) { RTree.Left.Childs.
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”的分支。但似乎理想的树还没有建成。我做得对吗?attachPoint
(和root
?)只是局部变量,所以attachPoint=RTree代码>不会影响树的结构。您需要搜索左树以找到插入点的父节点,然后修改父节点,以便parent.Right=attachPoint
attachPoint
(和root
?)只是局部变量,因此attachPoint=RTree代码>不会影响树的结构。您需要搜索左树以找到插入点的父节点,然后修改父节点,以便parent.Right=attachPoint
如果您已经包含了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;
}
如果您已经包含了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;
}
一个节点的最大子节点数是多少?这看起来不像二叉树,但节点包含一个子节点。看起来很奇怪。@Verarind您可以假设第二个子节点RTree
是二进制的,Left
实际上是childs[1],而Right
是childs[0]
节点的最大子节点数是多少?这看起来不像二叉树,但节点包含一个子节点。看起来很奇怪。@Verarind你可以假设第二个孩子RTree
是二进制的,Left
实际上是childs[1],而Right
是childs[0]