Skip to content

Instantly share code, notes, and snippets.

@frankhale
Created December 17, 2012 05:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save frankhale/4316043 to your computer and use it in GitHub Desktop.
Save frankhale/4316043 to your computer and use it in GitHub Desktop.
Trying to understand binary trees, I'm getting there but there is still some more to do.
public class BSPTreeNode<T>
{
public T Data { get; set; }
public BSPTreeNode<T> Parent { get; set; }
public BSPTreeNode<T> Left { get; set; }
public BSPTreeNode<T> Right { get; set; }
}
public class BSPTree<T>
{
private IComparer<T> comparer;
private BSPTreeNode<T> root;
public BSPTree()
{
comparer = Comparer<T>.Default;
}
public BSPTree(IComparer<T> comparer)
{
this.comparer = comparer;
}
public void Add(T data)
{
BSPTreeNode<T> node = new BSPTreeNode<T>()
{
Data = data
};
if (root == null)
root = node;
else
Add(root, node);
}
private void Add(BSPTreeNode<T> root, BSPTreeNode<T> node)
{
node.Parent = root;
if (comparer.Compare(node.Data, root.Data) <= 0)
{
if (root.Left == null)
root.Left = node;
else
Add(root.Left, node);
}
else
{
if (root.Right == null)
root.Right = node;
else
Add(root.Right, node);
}
}
public void Iterate(Action<BSPTreeNode<T>> action)
{
Iterate(root, action);
}
private void Iterate(BSPTreeNode<T> parent, Action<BSPTreeNode<T>> action)
{
action(parent);
if (parent.Left != null)
Iterate(parent.Left, action);
if (parent.Right != null)
Iterate(parent.Right, action);
}
}
class Program
{
static void Main(string[] args)
{
BSPTree<string> bstree = new BSPTree<string>();
bstree.Add("Hello");
bstree.Add("World");
bstree.Add("12345");
bstree.Add("67890");
bstree.Add("abcdef");
bstree.Iterate(node => Console.WriteLine("Data: {0} | Parent: {1}", node.Data, (node.Parent != null) ? node.Parent.Data : "null"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment