2015-05-09 117 views
0

我想知道是否有人可以幫助我。刪除C#樹中的節點

我想刪除C#樹中的一個節點,下面的代碼完全可以。但我不完全理解的是遍歷和刪除過程中聲明的所有節點都只是實際節點的副本,我無法看到它們如何影響實際節點並將它們彼此交換。我在C++中使用這種方法沒有問題,因爲我使用了指針,並且兩個指針可以同時指向一塊內存,但是我們並不使用C#。

class BinarySearchTree<T> 
{ 
    class Node 
    { 
     public Node Left; 
     public T Info; 
     public Node Right; 
    } 
    public bool DeleteItem(T item) 
    { 
     Node t = Root, s = null; 
     while (t != null && Compare(item, t.Info) != 0) 
     { 
      s = t; 
      t = (Compare(item, t.Info) <= 0) ? t.Left : t.Right; 
     } 

     if (t == null) 
      return false; 

     if (t.Left != null && t.Right != null) //node has 2 children 
     { 
      Node suc = t.Right, parent_suc = null; 
      while (suc.Left != null) 
      { 
       parent_suc = suc; 
       suc = suc.Left; 
      } 
      if (parent_suc == null) 
       t.Right = suc.Right; 
      else 
       parent_suc.Left = suc.Right; 
      t.Info = suc.Info; 
     } 
     else //node has either one child or no child at all 
     { 
      Node child = t.Left; 
      if (t.Right != null) 
       child = t.Right; 
      if (s == null) 
       Root = child; 
      else 
      { 
       if (s.Left == t) 
        s.Left = child; 
       else 
        s.Right = child; 
      } 
     } 
     return true; 
    } 
} 
+1

代碼中沒有副本,因爲Node是一個類,而不是結構。 –

+0

@ General-Doomer所以你的意思是例如「Node suc = t.Right」不會將值賦給新的內存?對? –

+0

是的,這行只複製鏈接(點),而不是內容 –

回答

3

Node類型是類,這是一引用類型。這意味着當您將其分配或複製到一個新變量時,它將創建一個新的參考到原始數據,而不是複製數據本身(相反將是值類型)。它確實與C++指針非常相似,但有一些區別(不使用指針算術,而是使用自動垃圾收集)。

請參閱this關於C#類型的MSDN文章,以及關於C++指針和C#引用的文章this