这可能是一个超级简单的问题,但我不知道如何处理Forms。
我需要在Winform的代码中调用一个Preorder遍历方法(在另一个类中实现),以便在Form接口的标签中打印Preorder。
所以我有一个BST类,其中有一个在Preorder中遍历树的方法。还有一种向树中插入值的方法。像这样:
namespace BinaryTree //the BST's class
{
public partial class BinarySearchTreeNode<T> where T : IComparable<T>
{
public void Insert(T value) //method for inserting
{
....
}
public IEnumerable<T> Preorder() //method for Preorder traversal
{
List<T> preOrdered= new List<T>();
if (_value != null)
{
preOrdered.Add(Value);
if (LeftChild != null) //
{
preOrdered.AddRange(LeftChild.Preorder());
}
if (RightChild != null) //
{
preOrdered.AddRange(RightChild.Preorder());
}
}
return preOrdered;
}
}
现在,为了使用这些操作,我有一个Windows窗体界面。它有用于创建新树、向树添加值(通过在inputTextBox中键入值并单击btnCreate)和将树显示给用户(通过PaintTree)的代码,但我还需要打印树的预购给用户。
假设我在界面中有一个标签,名为"预购标签";这就是我希望打印预订单的地方。
表单的代码如下所示:
namespace BinaryTree
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private BinarySearchTree<int> _tree;
void PaintTree()
{
if (_tree == null) return;
pictureBox1.Image = _tree.Draw();
}
private void btnCreate_Click(object sender, EventArgs e)
{
try
{
_tree = new BinarySearchTree<int>(new BinarySearchTreeNode<int>(int.MinValue));
PaintTree();
}
catch(NotImplementedException) { MessageBox.Show("There is no implementation!"); }
}
private void btnAdd_Click(object sender, EventArgs e)
{
try
{
var val = int.Parse(inputTextBox.Text); //makes a variable out of the input value from the user, to work with
if (_tree == null)
btnCreate_Click(btnCreate, new EventArgs());
_tree.Insert(val); //***calls the "Insert" method from the BST class, to insert the value to the tree
PaintTree(); //shows the user the tree
//**this is [I guess] where I need code for printing the tree in Preorder**
PreorderLabel.Text = ???????
inputTextBox.SelectAll();
this.Update();
}
catch (Exception exp) { MessageBox.Show(exp.Message); }
}
因此,当用户单击Add按钮(btAddd)时,树"_tree"不仅会调用Insert方法,还会调用PaintTree方法来显示树;还可以调用Preorder方法来打印标签"PreorderLabel"中的Preorder。
如何做到这一点?
我会非常高兴所有的帮助!
您可以使用带有如下分隔符字符串的String.Join(string separator, IEnumerable<string> values)
方法:
PreorderLabel.Text = String.Join("; ", _tree.PreOrder().Select(item => item.ToString()));
PreOrder()
方法将返回IEnumerable<int>
实例,因此我们需要做的只是将int
值转换为string
。