基于长分支的C#树
我有这样定义的树节点:基于长分支的C#树,c#,loops,recursion,tree,C#,Loops,Recursion,Tree,我有这样定义的树节点: class TreeNode : IEnumerable<TreeNode> { private readonly Dictionary<string, TreeNode> _childs = new Dictionary<string, TreeNode>(); public readonly string ID; public TreeNode Parent { get; private set; }
class TreeNode : IEnumerable<TreeNode>
{
private readonly Dictionary<string, TreeNode> _childs = new Dictionary<string, TreeNode>();
public readonly string ID;
public TreeNode Parent { get; private set; }
public int Level { get; set; }
public TreeNode(string id)
{
this.ID = id;
}
// some other methods
}
private void TreeReduction(TreeNode node)
{
while (node.Count() == 1)
{
node = node.GetFirstChild();
}
foreach (var child in node)
{
TreeReduction(child);
}
}
我把它叫做主节点。它看起来很好,正在通过树,但节点并没有被重写。我尝试了treenode的参数,但foreach循环有问题。我怎样才能把它修好让它工作?谢谢你对会发生什么做了很多假设,例如对单枝单叶树,你可以这样做
var redux = TreeReduction(rootNode, 0);
除此之外,关键的一点是递归方法返回一个可以设置为childnode的树节点
我忽略了父属性,因为它的setter是私有的。如果AddChild未设置它,则应将其公开并作为参数携带
private TreeNode TreeReduction(TreeNode node, int currentLevel)
{
if(node==null)
return null;
if(node.Count() == 1)
{
var redux = TreeReduction(node.GetFirstChild(), currentLevel);
return redux?? new TreeNode(node.ID{level=currentLevel});
}
var newNode = new TreeNode(node.ID{level=currentLevel});
foreach (var child in node)
{
var newChild = TreeReduction(child, currentLevel+1);
if(newChild!=null)
newNode.AddChild(newChild);
}
return newNode;
}