Cs 8128
Cs 8128

Reputation: 113

Deleting Binary Tree in C# .net

    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;
        }
}

The deleteTree function takes in the root of the binary tree and tries to delete the elements in post order. How ever,after setting every node to null,the original nodes a,b,c,d except root are still not null. They have the data field in them with left and right child set to null.Referenece equals for a,b,c,d with null returns false and for root it is true.

How do I set the original nodes also to null?

Upvotes: 0

Views: 378

Answers (2)

George Polevoy
George Polevoy

Reputation: 7681

The problem with your code is that references stored in node fields do not have to do with references in the calling context of method Main. root = null; references a variable from Main method scope. and deleteTree(ref root.left); references a field in a class instance.

Upvotes: 0

Servy
Servy

Reputation: 203835

If you write down your home address on a piece of paper and then burn that piece of paper does it destroy every piece of paper in the whole world that has your address written on it? Does burning that piece of paper destroy your house?

r.left contains an address to an object. You've destroyed that address by setting it to null. That does nothing to affect any other address, or the object itself.

Upvotes: 4

Related Questions