网上绝大部分的二叉树打印效果都十分潦草,也不够直观形象,最近自己用Java写了个打印器,可以实现如下效果
1 BinarySearchTree<Integer> bst1 = bst(new Integer[]{ 2 7, 4, 9, 2, 5, 8, 11, 1, 3, 6, 10, 12 3 }); 4 printer.treeln(bst1); 5 /* 6 7 7 / 8 4 9 9 / \ / 10 2 5 8 11 11 / \ \ / 12 1 3 6 10 12 13 */ 14 15 BinarySearchTree<Integer> bst2 = bst(new Integer[]{ 16 381, 12, 410, 9, 40, 394, 540, 17 35, 190, 476, 760, 146, 445, 18 600, 800 19 }); 20 printer.treeln(bst2); 21 /* 22 381 23 / 24 12 410 25 / \ / 26 9 40 394 540 27 / \ / 28 35 190 476 760 29 / / / 30 146 445 600 800 31 */ 32 33 printer.treeln(bst(new Integer[]{ 34 30, 10, 60, 5, 20, 40, 80, 35 15, 50, 70, 90 36 })); 37 /* 38 30 39 / 40 10 60 41 / \ / 42 5 20 40 80 43 / \ / 44 15 50 70 90 45 */ 46 47 printer.treeln(new NodeOperation() { 48 @Override 49 public Object root() { 50 return 8; 51 } 52 53 @Override 54 public Object left(Object node) { 55 if (node.equals(8)) return 3; 56 if (node.equals(3)) return 1; 57 if (node.equals(6)) return 4; 58 if (node.equals(14)) return 13; 59 return null; 60 } 61 62 @Override 63 public Object right(Object node) { 64 if (node.equals(8)) return 10; 65 if (node.equals(10)) return 14; 66 if (node.equals(3)) return 6; 67 if (node.equals(6)) return 7; 68 return null; 69 } 70 71 @Override 72 public Object string(Object node) { 73 return node; 74 } 75 }); 76 /* 77 8 78 / 79 3 10 80 / \ 81 1 6 14 82 / \ / 83 4 7 13 84 */ 85 86 printer.treeln(new NodeOperation() { 87 @Override 88 public Object root() { 89 return "Life"; 90 } 91 92 @Override 93 public Object left(Object node) { 94 if (node.equals("Life")) return "Animal"; 95 if (node.equals("Person")) return "Man"; 96 if (node.equals("Animal")) return "Cat"; 97 if (node.equals("Dog")) return "Teddy"; 98 return null; 99 } 100 101 @Override 102 public Object right(Object node) { 103 if (node.equals("Life")) return "Person"; 104 if (node.equals("Person")) return "Woman"; 105 if (node.equals("Animal")) return "Dog"; 106 if (node.equals("Dog")) return "SingleDog"; 107 return null; 108 } 109 110 @Override 111 public Object string(Object node) { 112 return node; 113 } 114 }); 115 /* 116 Life 117 / 118 Animal Person 119 / \ / 120 Cat Dog Man Woman 121 / 122 Teddy SingleDog 123 */
具体实现请看github:https://github.com/CoderMJLee/BinaryTrees
原文地址:https://www.cnblogs.com/mjios/p/10627606.html
时间: 2024-10-20 18:36:27