【发布时间】:2013-11-18 13:08:12
【问题描述】:
我有一个展开树,我想打印到文本区域。它正在控制台中打印,但我决定添加一个我想将树打印到 textArea 的 GUI。
public class Bst<Key extends Comparable<Key>, Value> {
private Node root;
private class Node {
private Key phone_number;
private Value contact_name;
private Node left, right;
public Node(Key phone_number, Value contact_name) {
this.phone_number = phone_number;
this.contact_name = contact_name;
}
}
public boolean contains(Key phone_number) {
return (get(phone_number) != null);
}
// return contact_name associated with the given phone_number
public Value get(Key phone_number) {
root = splay(root, phone_number);
int cmp = phone_number.compareTo(root.phone_number);
if (cmp == 0)
return root.contact_name;
else
return null;
}
public void printTree( )
{
if( isEmpty( ) )
System.out.println( "Empty tree" );
else
printTree( root );
}
private void printTree( Node t )
{
if ( t.left != null )
{
System.out.println( "Phone Number:" + t.phone_number.toString( ) + " Contact Name : " + t.contact_name.toString( ) );
printTree( t.left );
}
if (t.right != null)
{
printTree( t.right );
System.out.println( "name:" + t.phone_number.toString( ) + " Number : " + t.contact_name.toString( ) );
}
}
}
目前我的 printTree 有 void 返回类型,如上所示。
如何修改我的代码,以便能够将所有树值和键打印到 TextArea。我知道 setText() 采用字符串类型,但在这种情况下它不起作用(我认为),我怎样才能确保 print 方法将所有值输出到文本区域?
【问题讨论】:
-
至少发布完整代码。
-
我会传入
StringBuilder,只要有System.out的地方就调用append -
这似乎是实现访问者模式的好时机。
-
感谢@Danny 的提示。
标签: java binary-search-tree settext