2.直观打印二叉树
2019-07-22 本文已影响0人
山行牧野
首先,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);
}
}