0

私はこのように定義されたツリーノードを持っています:

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
}

これでキーワードからツリーを作成しましたが、親ツリーノードに1つの子があり、その子にも1つの子があり、一部のノードの後に​​2つの子があるブランチがあります。したがって、ここで、その1つの子すべてを(削除して)、少なくとも2つの子ノードが存在する「レベル」に減らしたいと思います。

私はこのようなことを試みました:

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

そしてそれをメインノードと呼びます。見た目は大丈夫で、ツリーを通過していますが、ノードは書き換えられません。treenodeのパラメーターを試しましたが、foreachループに問題があります。どうすればそれを修正して機能させることができますか?ありがとう

4

1 に答える 1

1

たとえば、単一分岐の単一葉の木に何が起こるかについて多くの仮定を立てると、このようなものを選ぶことができます。

var redux = TreeReduction(rootNode, 0);

これとは別に、重要なポイントは、再帰メソッドが子ノードとして設定できるTreeNodeを返すことです。

セッターがプライベートであるため、Parentプロパティを省略しました。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;
    }
于 2013-01-30T10:29:31.127 に答える