Reputation: 185
Ive starting learning C# with a background of c/c++. I am creating a simple BST but my insert function wont work. Any help would greatly be appreciated.
I get this kind of error when not passing by reference in c/c++. Since I created a two classes Node and BST, shouldn't they be passed by reference? Ive worked on this problem for a couple of hours and tried to change my code but with no luck.
public Node(int data)
{
this.data = data;
this.right = null;
this.left = null;
}
public Node Left
{
get { return left; }
set { left = value; }
}
public Node Right
{
get { return right; }
set { right = value; }
}
public int Data
{
get { return data; }
set { data = value; }
}
}
class BST
{
private Node root;
public BST()
{
root = null;
}
public Node Root
{
get { return root; }
set { root = value; }
}
public void Insert(int data)
{
if (root == null)
{
root = new Node(data);
}
else
{
InsertHelper(root, data);
}
}
public void InsertHelper( Node root, int data)
{
if (root == null)
{
root = new Node(data);
//return root;
}
if (root.Data > data)
{
InsertHelper(root.Left, data);
}
if (root.Data < data)
{
InsertHelper(root.Right, data);
}
}
Upvotes: 3
Views: 73
Reputation: 3544
You are assigning a new node to the argument pointer instead of original one. Insert
should be:
public void Insert(int data)
{
if (root == null)
{
root = new Node(data);
}
else
{
root = InsertHelper(root, data);
}
}
and InsertHelper
should be:
public Node InsertHelper( Node root, int data)
{
if (root == null)
return new Node(data);
if (root.Data > data)
{
root.Left = InsertHelper(root.Left, data);
}
if (root.Data < data)
{
root.Right = InsertHelper(root.Right, data);
}
return root;
}
In fact you don't even need Insert
since InsertHelper
already deals with root being null
Main method for testing:
public static void Main()
{
BST bst = new BST();
bst.Insert(5);
bst.Insert(6);
bst.Insert(4);
bst.Insert(7);
bst.Insert(3);
Console.WriteLine(bst.Root.Data + " ");
Console.WriteLine(bst.Root.Left.Data + " ");
Console.WriteLine(bst.Root.Right.Data + " ");
Console.WriteLine(bst.Root.Left.Left.Data + " ");
Console.WriteLine(bst.Root.Right.Right.Data + " ");
}
Upvotes: 1