C#二叉搜索树

标签 c# binary-search-tree

我正在为我教授给的二叉搜索树上的一些代码制作一个测试用例

public static void Main(string [] args)
{
    //on my prof's code, public class BinSearchTree<T>
    BinSearchTree<int> myTree = new BinSearchTree<int>();

    myTree.Insert(10);
    myTree.Insert(15);
    myTree.Insert(5);
    myTree.Insert(2);
    myTree.Insert(1);

    Console.WriteLine(myTree.ToString());
    Console.ReadKey();
}

它编译,但它显示

BinSearchTree`1[System.Int32]

有人能告诉我为什么会这样显示吗?

我教授的代码:

public class BinSearchTree<T> where T : IComparable<T>
{
private class OurTreeNode<T>
{
    public T Data { get; set; }
    public OurTreeNode<T> Left;
    public OurTreeNode<T> Right;
    public OurTreeNode(T d = default(T), OurTreeNode<T> leftnode = null, OurTreeNode<T> rightnode = null)
    {
        Data = d;
        Left = leftnode;
        Right = rightnode;
    }

    public override string ToString()
    {
        return Data.ToString();
    }
}
//...other methods

//prof's Insert method
public void Insert(T newItem)
{
    mRoot = Insert(newItem, mRoot);
}
private OurTreeNode<T> Insert(T newItem, OurTreeNode<T> pTmp)
{
    if (pTmp == null)
        return new OurTreeNode<T>(newItem, null, null);
    else if (newItem.CompareTo(pTmp.Data) < 0)
        pTmp.Left = Insert(newItem, pTmp.Left);
    else if (newItem.CompareTo(pTmp.Data) > 0)
        pTmp.Right = Insert(newItem, pTmp.Right);
    else
        throw new ApplicationException("...");

    return pTmp;
}
}

我尝试在 Insert 方法之后添加一个 ToString() 方法,但是当我使用 foreach 时它给了我一个错误。有没有一种不用做太多额外方法就可以显示的方法呢?

最佳答案

该类使用默认的(对象的)ToString() 实现。您有 2 个选择:

  • 遍历树的元素并自己打印
  • 要求作者实现/覆盖 ToString() 方法

关于C#二叉搜索树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39716810/

相关文章:

c# - 为什么选择 SharpDevelop 而不是 Visual Studio 来使用 C# 进行编码?

algorithm - 删除二叉树中节点的方法

java - BST 层级顺序遍历 list.clear() and list = new ArrayList

c++ - 我坚持用 C++ 填充我的基于数组的 BST

c# - 如何在点击按钮时显示通知提示? Windows 手机

c# - 如何使用 Fluent NHibernate 映射序列化/反序列化元素列表?

c# - 如何在不执行 Queryable 的情况下以通用方式替换 Queryable<T> 中的列

c# - Autofac - 内存泄漏

java - JAVA 中的递归前序遍历运行直至堆栈溢出(BST)

java - 通用 BinarySearchTree 中的 PostOrder 输出 (Java)