• 01.如何直观的打印一棵树


    1.java版本

    //java语言
    
    public class PrintBinaryTree {
    
        public static class Node {
            public int value;
            public Node left;
            public Node right;
    
            public Node(int data) {
                this.value = data;
            }
        }
    
        public static void printTree(Node head) {
            System.out.println("Binary Tree:");
            printInOrder(head, 0, "H", 17);
            System.out.println();
        }
    
        public 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);
        }
    
        public static String getSpace(int num) {
            String space = " ";
            StringBuffer buf = new StringBuffer("");
            for (int i = 0; i < num; i++) {
                buf.append(space);
            }
            return buf.toString();
        }
    
        public static void main(String[] args) {
            Node head = new Node(1);
            head.left = new Node(-222222222);
            head.right = new Node(3);
            head.left.left = new Node(Integer.MIN_VALUE);
            head.right.left = new Node(55555555);
            head.right.right = new Node(66);
            head.left.left.right = new Node(777);
            printTree(head);
    
            head = new Node(1);
            head.left = new Node(2);
            head.right = new Node(3);
            head.left.left = new Node(4);
            head.right.left = new Node(5);
            head.right.right = new Node(6);
            head.left.left.right = new Node(7);
            printTree(head);
    
            head = new Node(1);
            head.left = new Node(1);
            head.right = new Node(1);
            head.left.left = new Node(1);
            head.right.left = new Node(1);
            head.right.right = new Node(1);
            head.left.left.right = new Node(1);
            printTree(head);
    
        }
    
    }

    2.C++版本(待整理)

    ……

  • 相关阅读:
    【阿里的感悟】质量该如何做? .(转载)
    java linux 配置环境
    Spring Bean属性绑定Bean返回值
    Spring BeanNameAutoProxyCreator 与 ProxyFactoryBean
    Spring Aop之(二)Aop 切面声明和通知
    Ubuntu开机自动启动Script
    转战博客园!
    linux 系统管理11 ——系统安全及应用
    linux awk
    Rsync数据同步工具
  • 原文地址:https://www.cnblogs.com/paulprayer/p/10101035.html
Copyright © 2020-2023  润新知