This is a simple implementation of a generic binary tree that holds elements of type T. I was wondering if there was something that could be done better (especially in the EnumerateNodes methods).
using System.Collections.Generic;
namespace DataStructures.Node
{
/// <summary>
/// Implements a generic binary tree.
/// </summary>
/// <typeparam name="T">The type of the nodes</typeparam>
public class Node<T>
{
#region Private attributes
private T _node = default(T);
private Node<T> _leftChild = default(Node<T>);
private Node<T> _rightChild = default(Node<T>);
#endregion
#region Constructor
public Node()
{
_node = default(T);
_leftChild = null;
_rightChild = null;
}
public Node(T node)
{
_node = node;
_leftChild = null;
_rightChild = null;
}
#endregion
#region Accessors
public T Value
{
get { return _node; }
set { _node = value; }
}
public Node<T> LeftChild
{
get { return _leftChild; }
set { _leftChild = value; }
}
public Node<T> RightChild
{
get { return _rightChild; }
set { _rightChild = value; }
}
/// <summary>
/// Returns the total number of elements in the tree.
/// </summary>
public int Count
{
get { return count(); }
}
#endregion
#region Private methods
private int count()
{
if (_leftChild == null && _rightChild == null)
return 1;
if (_leftChild == null)
return 1 + _rightChild.count();
if (_rightChild == null)
return 1 + _leftChild.count();
else
return 1 + _leftChild.count() + _rightChild.count();
}
#endregion
#region Public methods
/// <summary>
/// Adds the element on the right branch of the node.
/// </summary>
/// <param name="rightBranch">Node to add on the right side of the node.</param>
public void AddRight(Node<T> rightBranch)
{
_rightChild = rightBranch;
}
/// <summary>
/// Adds the element on the left branch of the node.
/// </summary>
/// <param name="leftBranch">Node to add on the left side of the node.</param>
public void AddLeft(Node<T> leftBranch)
{
_leftChild = leftBranch;
}
public IEnumerable<T> EnumerateNodes()
{
yield return _node;
if (_leftChild != null)
foreach (T child in _leftChild.EnumerateNodes())
yield return child;
if (_rightChild != null)
foreach (T child in _rightChild.EnumerateNodes())
yield return child;
}
#endregion
}
}
T[]
(orList<T>
) - which helps avoid heap fragmentation. \$\endgroup\$