zoukankan      html  css  js  c++  java
  • 打印一棵二叉树


    /**
    * 打印一棵二叉树
    * <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;
    }

    }

    }

    /* 如有意见或建议,欢迎评论区留言;如发现代码有误,欢迎批评指正 */
  • 相关阅读:
    Widget Factory
    233 Matrix
    青蛙的约会
    Longge's problem
    密码解锁
    SQFREE
    GCD
    [WC2011]最大XOR和路径
    [HNOI2011]XOR和路径
    [ZJOI2010]排列计数
  • 原文地址:https://www.cnblogs.com/laydown/p/12944833.html
Copyright © 2011-2022 走看看