1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
|
public class TreePrinter { private static void linuxStyle(TreeNode root, StringBuilder sb, String prefix, String childPrefix) { if (root == null) { return; } sb.append(prefix); sb.append(root.val); sb.append("\n"); linuxStyle(root.right, sb, childPrefix + "├── ", childPrefix + "│ "); linuxStyle(root.left, sb, childPrefix + "└── ", childPrefix + " "); }
public static StringBuilder getLinuxStyle(TreeNode root) { StringBuilder sb = new StringBuilder(); linuxStyle(root, sb, "", ""); return sb; }
public static void prtLinuxStyle(TreeNode root) { System.out.println(getLinuxStyle(root).toString()); }
public static StringBuilder horizontalStyle(TreeNode root, StringBuilder sb) { if (root.right != null) { horizontalStyle(root.right, sb, true, ""); } sb.append(root.val).append("\n"); if (root.left != null) { horizontalStyle(root.left, sb, false, ""); } return sb; }
private static void horizontalStyle(TreeNode root, StringBuilder sb, boolean isRight, String indent) { if (root.right != null) { horizontalStyle(root.right, sb, true, indent + (isRight ? " " : " | ")); } sb.append(indent); sb.append(isRight ? " /" : " \\"); sb.append("----- "); sb.append(root.val).append("\n"); if (root.left != null) { horizontalStyle(root.left, sb, false, indent + (isRight ? " | " : " ")); } }
public static void prtHorizontalStyle(TreeNode root) { System.out.println(horizontalStyle(root, new StringBuilder()).toString()); }
public static void main(String[] args) { int[] pre = {1, 2, 4, 7, 3, 5, 6, 8}; int[] in = {4, 7, 2, 1, 5, 3, 8, 6}; TreeNode root = Tree.mkTree(pre, in); TreePrinter.prtLinuxStyle(root); TreePrinter.prtHorizontalStyle(root);
pre = new int[] {8, 4, 2, 1, 3, 6, 5, 7, 12, 10, 9, 11, 14, 13, 20, 15}; in = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 20}; root = Tree.mkTree(pre, in); TreePrinter.prtLinuxStyle(root); TreePrinter.prtHorizontalStyle(root); } }
|