首先,Node.java文件同上
然后打印:
public class printTree {
public String getSpace(int num)
{
String space = " ";
StringBuffer buf = new StringBuffer("");
for(int i=0;i<num;i++)
{
buf.append(space);
}
return buf.toString();
}
public void printBinaryTree(Node head)
{
System.out.println("BinaryTree:");
printInOrder(head,0,"H",17);
System.out.println();
}
public void printInOrder(Node head,int height,String to,int len)
{
if(head == null)
{
return;
}
printInOrder(head.left, height+1, "v", len);
String val = to+head.value+to;
int lenV = val.length();
int lenL = (len - lenV)/2;
int lenR = len - lenL - lenV;
val = getSpace(lenL)+val+getSpace(lenR);
System.out.println(getSpace(height*len)+val);
printInOrder(head.right,height+1,"^",len);
}
}
网友评论