2014-11-17 4 views
0
public class Program 
     { 
      public static void Main() 
      { 
       BinaryTree bt = new BinaryTree(); 

       Node r = new Node(1); 
       Node a = new Node(2); 
       Node b = new Node(3); 
       Node c = new Node(4); 
       Node d = new Node(5); 

       r.left = a; 
       r.right = b; 
       a.left = c; 
       a.right = d; 

       bt.deleteTree(ref r); 

       Console.WriteLine("Is r deleted:" + ReferenceEquals(r, null)); 
       Console.WriteLine("Is a deleted:" + ReferenceEquals(a, null)); 
       Console.WriteLine("Is b deleted:" + ReferenceEquals(b, null)); 
       Console.WriteLine("Is c deleted:" + ReferenceEquals(c, null)); 
       Console.WriteLine("Is d deleted:" + ReferenceEquals(d, null)); 
    } 
    } 

public class Node 
    { 
     public int data; 
     public Node left=null; 
     public Node right=null; 

     public Node(int x) 
     { 
      data = x; 
     } 
    } 

public class BinaryTree 
    { 

     public void deleteTree(ref Node root) 
     { 
      if (root == null) return; 

      deleteTree(ref root.left); 
      deleteTree(ref root.right); 
      Console.WriteLine(root.data); 
      root = null; 
     } 
} 

deleteTree 함수는 이진 트리의 루트를 가져 와서 해당 순서대로 요소를 삭제하려고 시도합니다. 모든 노드를 null로 설정 한 후 루트를 제외한 원본 노드 a, b, c, d는 여전히 null이 아닙니다. 그들은 왼쪽과 오른쪽 자식을 null로 설정 한 데이터 필드를 가지고 있습니다. a, b, c, d가 null 인 경우 Referenece는 false를 반환하고 루트 인 경우 true를 반환합니다.C# .net에서 이진 트리 삭제

원래 노드도 null로 설정하려면 어떻게해야합니까?

+6

'a'또는 'b'또는 'c'또는 'd'를 참조로 전달하지 않았으므로 여전히 원래 노드를 참조합니다. 그러나이 모든 운동은 잘못된 것입니다. C#은 GC 언어입니다. 그냥'r = null'을하면 끝난 것입니다. –

+0

r.left == a가 아닌가요? 두 객체가 똑같은 객체를 참조하는 것을 의미합니까? 그리고 ref.left를 통과했습니다. –

+0

ref로'r.left'를 전달했지만'a'가 아닙니다. 그것에 대해 생각해보십시오 :'int a = 42; int b = a; SomeFunction (ref b);'SomeFunction'이'b'를 수정하면'a'도 수정해야합니까? –

답변

4

집 주소를 종이에 적어서 그 종이를 태우면 주소가 쓰여진 전세계 모든 종이가 파괴됩니까? 종이 조각을 태우면 집안이 파괴됩니까?

r.left에는 개체에 대한 주소가 포함되어 있습니다. 이 번호를 null로 설정하여 주소 인을 삭제했습니다. 그것은 다른 주소 나 객체 자체에 영향을주지 않습니다.

+0

+1 종이 조각에 대한 참조를 잘 비교합니다. 그러나 객체의 인스턴스로 작업하는 것은 집 자체를 불타는 것과 같습니다. –

0

코드의 문제점은 노드 필드에 저장된 참조가 메소드 Main의 호출 컨텍스트에서 참조와 관련이 없다는 점입니다. root = null;은 Main method scope에서 변수를 참조합니다. and deleteTree(ref root.left);은 클래스 인스턴스의 필드를 참조합니다.