【问题标题】:C# tree from keywords reduction long branches关键字减少长分支的C#树
【发布时间】:2013-01-14 00:49:06
【问题描述】:

我有这样定义的树节点:

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
}

我通过这个关键字创建了树,现在我有时在父树节点有一个孩子的地方分支,那个孩子也可能有一个孩子,在一些节点之后有 2 个孩子。所以我现在想将所有一个子节点(删除它)减少到至少有 2 个子节点的“级别”。

我尝试过这样的事情:

private void TreeReduction(TreeNode node)
    {
        while (node.Count() == 1)
        {
            node = node.GetFirstChild();
        }
        foreach (var child in node)
        {
            TreeReduction(child);
        }
    }

我把它称为主节点。它看起来不错,它正在遍历树,但节点没有被重写。我尝试了 treenode 的参数,但我遇到了 foreach 循环的问题。我该如何修复它以使其正常工作?谢谢

【问题讨论】:

    标签: c# loops recursion tree


    【解决方案1】:

    对会发生什么做出许多假设,例如对单枝单叶树,您可以选择这样的事情。

    var redux = TreeReduction(rootNode, 0);
    

    除此之外,关键是让您的递归方法返回一个 TreeNode,您可以将其设置为子节点。

    我省略了 Parent 属性,因为它的 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;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多