Andre is right to a certain extent, but his solution does not build you a full tree - he overwrites any existing node when you provide a different value.
If your tree values are meant to create a tree such as
5
/ \
2
/ \
1 3
Then you need to check is nodes exist already, before creating new ones.
In addition, I would not pass through the node to your add method: make it work on the current instance instead:
public class BTree
{
public int Value { get; set; }
public BTree Left { get; set; }
public BTree Right { get; set; }
public BTree() : this(0) { }
public BTree(int val)
{
Value = val;
}
public void Add(int val)
{
if (Value == 0)
{
Value = val;
}
else if (Value > val)
{
if (Left == null)
{
Left = new BTree(val);
}
else
{
Left.Add(val);
}
}
else
{
if (Right == null)
{
Right = new BTree(val);
}
else
{
Right.Add(val);
}
}
}
}
Two other things occur:
1) Your Count is pretty useless: it returns the total number of nodes that have been cretaed, rather than the number which are in use, or which are involved in this tree. If you overwrite a node (as Andre does in his example), it does not decrease the count. You would be better off implementing a Count property which counted the number of nodes in teh tree from this point:
public int Count
{
get
{
int count = 1;
if (Left != null) count += Left.Count;
if (Right != null) count += Right.Count;
return count;
}
}
2) You probably don't want a Print method - that word has a particular meaning in computing. Instead, consider providing a ToString method which returns the whole tree as a string:
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append(Value.ToString());
if (Left != null || Right != null)
{
sb.Append(":(");
if (Left != null)
{
sb.Append(Left.ToString());
}
sb.Append(",");
if (Right != null)
{
sb.Append(Right.ToString());
}
sb.Append(")");
}
return sb.ToString();
}