2013-07-09 41 views
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); 

如何从树上删除子?

回答

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); 
} 
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); 
} 
+0

theTree.item.Remove(toDelete);只在树的第一级检查。如果我想删除的节点处于第四级,该怎么办? –

+0

OP表示他没有要删除的“Tree”节点,他只有id值。 – Servy

+0

“我有一个方法,在树中搜索给定的ID,我尝试使用该方法,然后将节点设置为空” –