2013-07-09 77 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,我嘗試使用該方法,然後將節點設置爲空」 –