Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# - Simple Binary Tree

Tags:

c#

binary-tree

So, I have been learning C# over the past month and at the moment I am struggling with Binary Trees.

My question is that How am I able to call my tree to the Console Window? I've Tried Console.WriteLine(tree.Data); But this seems to Write 54 to my Console Window.

Here is my code if you need to check it out:

Main File

static void Main(string[] args)
{
    //Creating the Nodes for the Tree
    Node<int> tree = new Node<int>('6');
    tree.Left = new Node<int>('2');
    tree.Right = new Node<int>('5');  

    Console.WriteLine("Binary Tree Display");
    Console.WriteLine(tree.Data);
    Console.ReadLine();
}

Node Class

class Node<T> where T : IComparable
{
    private T data;
    public Node<T> Left, Right;

    public Node(T item)
    {
        data = item;
        Left = null;
        Right = null;
    }
    public T Data
    {
        set { data = value; }
        get { return data; }
    }
}

Are there any other methods of calling my Tree? or am I doing something wrong?

like image 287
Angelrawzz Avatar asked Jul 30 '13 14:07

Angelrawzz


1 Answers

The reason why it's just showing 54 is because that is the what (int)'6' is!

You're calling tree.Data which returns in this case '6' cast to int.


I imagine what you're trying to do is either return 6 which you could do by using

new Node<char>('6'); 

or by

new Node<int>(6);

(More in separate answer, removed for clarity)

like image 133
dav_i Avatar answered Sep 20 '22 19:09

dav_i