在MSDN上有一篇关于二叉树和如何创建自定义二叉树这里的优秀文章。
问题
代码是below.It是有点长,但我只是粘贴它以供参考(只要一瞥就能告诉大家)。
实际上,我的问题是,如果我确实实现了如下所示的自定义二叉树,我应该首先为每个Node, NodesList, BinaryTree, BinaryTreeNode (4个类)定义一个接口,以便以后进行单元测试,还是在本例中不需要它。我看到.net中的许多集合实现了IEnumerable,我应该这样做吗,还是这里不需要这样做呢?
public class Node<T>
{
// Private member-variables
private T data;
private NodeList<T> neighbors = null;
public Node() {}
public Node(T data) : this(data, null) {}
public Node(T data, NodeList<T> neighbors)
{
this.data = data;
this.neighbors = neighbors;
}
public T Value
{
get
{
return data;
}
set
{
data = value;
}
}
protected NodeList<T> Neighbors
{
get
{
return neighbors;
}
set
{
neighbors = value;
}
}
}
}节点类
public class NodeList<T> : Collection<Node<T>>
{
public NodeList() : base() { }
public NodeList(int initialSize)
{
// Add the specified number of items
for (int i = 0; i < initialSize; i++)
base.Items.Add(default(Node<T>));
}
public Node<T> FindByValue(T value)
{
// search the list for the value
foreach (Node<T> node in Items)
if (node.Value.Equals(value))
return node;
// if we reached here, we didn't find a matching node
return null;
}
}最后
public class BinaryTreeNode<T> : Node<T>
{
public BinaryTreeNode() : base() {}
public BinaryTreeNode(T data) : base(data, null) {}
public BinaryTreeNode(T data, BinaryTreeNode<T> left, BinaryTreeNode<T> right)
{
base.Value = data;
NodeList<T> children = new NodeList<T>(2);
children[0] = left;
children[1] = right;
base.Neighbors = children;
}
public BinaryTreeNode<T> Left
{
get
{
if (base.Neighbors == null)
return null;
else
return (BinaryTreeNode<T>) base.Neighbors[0];
}
set
{
if (base.Neighbors == null)
base.Neighbors = new NodeList<T>(2);
base.Neighbors[0] = value;
}
}
public BinaryTreeNode<T> Right
{
get
{
if (base.Neighbors == null)
return null;
else
return (BinaryTreeNode<T>) base.Neighbors[1];
}
set
{
if (base.Neighbors == null)
base.Neighbors = new NodeList<T>(2);
base.Neighbors[1] = value;
}
}
}
public class BinaryTree<T>
{
private BinaryTreeNode<T> root;
public BinaryTree()
{
root = null;
}
public virtual void Clear()
{
root = null;
}
public BinaryTreeNode<T> Root
{
get
{
return root;
}
set
{
root = value;
}
}
}发布于 2013-08-30 22:58:08
没有回答,太长而不能发表评论:
将集合公开为IEnumerable总是一个好主意,因为在这种情况下可以很容易地应用LINQ查询。
二叉树本身是非常无用的,内部细节(节点)甚至不那么有趣。因此,将内部细节公开为接口可能是没有用的。将二叉树公开为特定的接口也可能是过分的--如果您需要它来表示某种排序结构IList/ICollection,或者可能是IDictionary,可能就足够了。
请注意,如果您正在构建二叉树作为其他几个有趣集合的基础,您可能会考虑接口,但它应该由测试特定代码片段的需求驱动。
https://stackoverflow.com/questions/18542468
复制相似问题