JavaScriptGrasshopper JavaScriptGrasshopper - 16 days ago 8
C# Question

C# - Binary Tree Issues

To the best of my knowledge my program should work, however, I'm having difficulties with the ref keyword. We aren't expected to use an Insert() method, yet. However, I'm having a hard time trying to use the traverse methods as every time I get an error, it's regarding the ref either an argument is missing or something else. I know I've probably messed up my Main method, but that's due to experimenting and trying to get it to work. I do have a NodeClass with Get and Setter methods, however, the issue is essentially the ref keyword. What am I missing? I've added string I get an error, I've tried to use buffer I get an error.

BinaryTree Class-

class BinTree<T> where T : IComparable
{
private Node<T> root;

public BinTree() //creates an empty tree
{
root = null;
}
public BinTree(Node<T> node) //creates a tree with node as the root
{
root = node;
}

public void InOrder(ref string buffer)
{
inOrder(root, ref buffer);
}

private void inOrder(Node<T> tree, ref string buffer)
{
if (tree != null)
{
inOrder(tree.Left, ref buffer);
buffer += tree.Data.ToString() + ",";
inOrder(tree.Right, ref buffer);
}

}

public void Preorder(ref string buffer)
{
PreOrder(root, ref buffer);
}

public void PreOrder(Node<T> tree, ref string buffer)
{
if (tree != null)
{
buffer += tree.Data.ToString() + ",";
PreOrder(tree.Left, ref buffer);
PreOrder(tree.Right, ref buffer);
}
}

public void postOrder( ref string buffer)
{
PostOrder(root, ref buffer);
}

public void PostOrder(Node<T> tree, ref string buffer)
{
if (tree != null)
{

PostOrder(tree.Left, ref buffer);
PostOrder(tree.Right, ref buffer);
buffer += tree.Data.ToString() + ",";
}
}
}


Program Class-

class Program
{
static void Main(string[] args)
{
BinTree<int> tree = new BinTree<int>();

Node<int> root = new Node<int>(6);
root.Left = new Node<int>(15);
root.Left.Right = new Node<int>(654);

tree.InOrder(ref , root.Data);




System.Console.WriteLine();
Console.ReadLine();
}
}


Could someone possibly help me? Thank you.

Apologises in advance if it's something obvious.

Answer

From the above common chain:

  • You need to pass the root node into the binTree otherwise it will not be able to do anything in the inOrder methods. (BinTree<int> tree = new BinTree<int>();)
  • You need a string to pass into the inOrder method call. You can use StringBuilder to improve performance and remove reliance on ref

The fiddle contains a copy of the code with adjustments.