C # - Simple binary tree

So, I studied C # in the last month, and at the moment I'm struggling with binary trees.

My question is, how can I name my tree in the console window? I tried Console.WriteLine(tree.Data); But this is like writing 54 to my console window.

Here is my code if you need to check it:

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 ways to call my tree? or am i doing something wrong?

+6
source share
4 answers

The reason it just shows 54 is because this is what (int)'6' is!

You call tree.Data , which in this case returns a '6' value in int .


I assume that you are trying to do either return 6 , which you could do using

 new Node<char>('6'); 

or

 new Node<int>(6); 

( See more in a separate answer removed for clarity )

+7
source
 Node<int> tree = new Node<int>(6); 

6, not '6'. Now the expected value will be printed. Your code silently adds a char value of '6' to an integer that gives a result of 54.

+2
source

( Transfer from the previous answer for clarity )

If you are trying to return all the data for your Node<T> , I think the best way to do this is to override the ToString method in your Node<T> class as follows:

 public override string ToString() { var leftString = this.Left != null ? this.Left.ToString() : "null"; var rightString = this.Right != null ? this.Right.ToString() : "null"; var dataString = this.Data != null ? this.Data.ToString() : "null"; leftString = String.Join("\n", leftString.Split('\n').Select(a => "\t" + a)); rightString = String.Join("\n", rightString.Split('\n').Select(a => "\t" + a)); return String.Format("\nData: {0}\n" + "Left: {1}\n" + "Right: {2}", dataString, leftString, rightString); } 

Then call Console.WriteLine(tree.ToString()); , which will result in the following:

 Data: 54 Left: Data: 50 Left: null Right: null Right: Data: 53 Left: null Right: null 

This is not the most beautiful implementation, but I think it proves the point.

For a more beautiful implementation see this answer

+2
source

I believe that the best way to do this is to implement a short recursive tree traversal algorithm that outputs the value of each node in the order in which you solve it. Regarding the availability of a pre-written method for this in the C # libraries, I don't know about that. Good luck

0
source

Source: https://habr.com/ru/post/950633/


All Articles