1

私はツリーを表すクラスを持っています:

public class Tree
{
    public String id { get; set; }
    public String text { get; set; }
    public List<Tree> item { get; set; }
    public string im0 { get; set; }
    public string im1 { get; set; }
    public string im2 { get; set; }
    public String parentId { get; set; }

    public Tree()
    {
        id = "0";
        text = "";
        item = new List<Tree>();
    }
}

ツリーは次のようになります。

tree    {Tree}  Tree
  id    "0" string
  im0   null    string
  im1   null    string
  im2   null    string
  item  Count = 1   System.Collections.Generic.List<Tree>
    [0] {Tree}  Tree
            id  "F_1"   string
            im0 "fC.gif"    string
            im1 "fO.gif"    string
            im2 "fC.gif"    string
            item    Count = 12  System.Collections.Generic.List<Tree>
            parentId    "0" string
            text    "ok"    string
    parentId    null    string
    text    ""  string

id = someId のノードを削除するにはどうすればよいですか?

たとえば、id = "F_123" のノードを削除するにはどうすればよいですか? その子もすべて削除する必要があります。

特定のIDをツリーで検索するメソッドがあります。そのメソッドを使用してから、ノードを null に設定しようとしましたが、機能しません。

これが私が今まで得たものです:

//This is the whole tree:
Tree tree = serializer.Deserialize<Tree>(someString);

//this is the tree whose root is the parent of the node I want to delete:
List<Tree> parentTree = Tree.Search("F_123", tree).First().item;

//This is the node I want to delete:
var child = parentTree.First(p => p.id == id);

ツリーから子を削除するにはどうすればよいですか?

4

2 に答える 2

1

したがって、これは、特定のノードの親を取得できるかなり単純なトラバーサル アルゴリズムです。再帰を使用するのではなく、明示的なスタックを使用してそうします。

public static Tree GetParent(Tree root, string nodeId)
{
    var stack = new Stack<Tree>();
    stack.Push(root);

    while (stack.Any())
    {
        var parent = stack.Pop();

        foreach (var child in parent.item)
        {
            if (child.id == nodeId)
                return parent;

            stack.Push(child);
        }
    }

    return null;//not found
}

これを使用すると、ノードの親を見つけて直接の子孫からノードを削除するだけで、ノードを簡単に削除できます。

public static void RemoveNode(Tree root, string nodeId)
{
    var parent = GetParent(root, nodeId).item
        .RemoveAll(child => child.id == nodeId);
}
于 2013-07-09T17:47:18.720 に答える
0

削除するノードの親ノードを見つけます (id=F_1)。再帰的にツリーから削除します

// something like
Tree parent = FindParentNodeOf("F_1");
var child = parent.Items.First(p=> p.id="F_1");
RecurseDelete(parent, child);

private void RecurseDelete(Tree theTree, Tree toDelete)
{
    foreach(var child in toDelete.item)
       RecurseDelete(toDelete, child);

    theTree.item.Remove(toDelete);
}
于 2013-07-09T12:12:11.183 に答える