fork download
  1. import java.lang.reflect.Array;
  2. import java.util.ArrayDeque;
  3.  
  4. class Ideone {
  5. public static void main(String[] args) {
  6. Tree tree = create_tree();
  7.  
  8. System.out.println("るーぷ");
  9. dump_loop(tree);
  10.  
  11. System.out.println("さいき");
  12. dump_recursive(tree);
  13. }
  14.  
  15. static void dump_loop(Tree tree) {
  16. ArrayDeque<Tree> stack = new ArrayDeque<>();
  17. stack.push(tree);
  18.  
  19. while (stack.size() > 0) {
  20. Tree parent = stack.pop();
  21.  
  22. System.out.println(parent.value);
  23.  
  24. for (Tree child : reverse(parent.children)) {
  25. stack.push(child);
  26. }
  27. }
  28. }
  29.  
  30. @SuppressWarnings("unchecked")
  31. static <T> T[] reverse(T[] src) {
  32. T[] dest = (T[]) Array.newInstance(src.getClass().getComponentType(), src.length);
  33.  
  34. for (int low = 0, high = dest.length - 1; low <= high; low++, high--) {
  35. dest[low] = src[high];
  36. dest[high] = src[low];
  37. }
  38.  
  39. return dest;
  40. }
  41.  
  42. static void dump_recursive(Tree tree) {
  43. System.out.println(tree.value);
  44. dump_sub_recursive(tree.children, 0);
  45. }
  46.  
  47. static void dump_sub_recursive(Tree[] children, int index) {
  48. if (index < children.length) {
  49. dump_recursive(children[index]);
  50. dump_sub_recursive(children, index + 1);
  51. }
  52. }
  53.  
  54. static Tree create_tree() {
  55. Tree tree12 = new Tree("12");
  56. Tree tree11 = new Tree("11");
  57. Tree tree10 = new Tree("10");
  58. Tree tree9 = new Tree("9");
  59. Tree tree8 = new Tree("8");
  60. Tree tree7 = new Tree("7");
  61. Tree tree6 = new Tree("6");
  62. Tree tree5 = new Tree("5", tree10, tree11, tree12);
  63. Tree tree4 = new Tree("4");
  64. Tree tree3 = new Tree("3", tree6, tree7, tree8, tree9);
  65. Tree tree2 = new Tree("2", tree4, tree5);
  66. Tree tree1 = new Tree("1", tree2, tree3);
  67. return tree1;
  68. }
  69.  
  70. static class Tree {
  71. String value;
  72. Tree[] children;
  73.  
  74. Tree(String value, Tree... children) {
  75. this.value = value;
  76. this.children = children;
  77. }
  78. }
  79. }
  80.  
Success #stdin #stdout 0.09s 321600KB
stdin
Standard input is empty
stdout
るーぷ
1
2
4
5
10
11
12
3
6
7
8
9
さいき
1
2
4
5
10
11
12
3
6
7
8
9