首页 > 其他 > 详细

打印一棵二叉树

时间:2020-05-23 23:08:01      阅读:64      评论:0      收藏:0      [点我收藏+]

/**
* 打印一棵二叉树
* <p>
* 中序遍历
*/
public class PrintBT {

public static void printTree(Node head) {
System.out.println("Binary Tree:");
printInOrder(head, 0, "H", 17);
System.out.println();
}

private static void printInOrder(Node head, int height, String to, int len) {
if (head == null) {
return;
}
printInOrder(head.right, height + 1, "v", len);
String val = to + head.value + to;
int lenM = val.length();
int lenL = (len - lenM) / 2;
int lenR = len - lenM - lenL;
val = getSpace(lenL) + val + getSpace(lenR);
System.out.println(getSpace(height * len) + val);
printInOrder(head.left, height + 1, "^", len);
}

private static String getSpace(int num) {
String space = " ";
StringBuilder builder = new StringBuilder();
for (int i = 0; i < num; i++) {
builder.append(space);
}
return builder.toString();
}

/**
* 二叉树结构
*/
public static class Node {

public int value;

public Node left;

public Node right;

public Node(int data) {
this.value = data;
}

}

}

/* 如有意见或建议,欢迎评论区留言;如发现代码有误,欢迎批评指正 */

打印一棵二叉树

原文:https://www.cnblogs.com/laydown/p/12944833.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!