fork download
  1. import java.util.*;
  2. import java.lang.*;
  3. import java.io.*;
  4.  
  5. class Node {
  6. public Double value;
  7. public List<Node> children;
  8.  
  9. public Node(Double value) {
  10. this.value = value;
  11. this.children = new ArrayList<Node>();
  12. }
  13. public void addChild(Node node) {
  14. children.add(node);
  15. }
  16. public static Node createSample() {
  17. Node node = new Node(10.0);
  18. Node node1 = new Node(15.0);
  19. Node node2 = new Node(6.0);
  20. Node node3 = new Node(11.0);
  21. Node node4 = new Node(14.0);
  22. Node node5 = new Node(5.0);
  23. node.addChild(node1);
  24. node.addChild(node2);
  25. node.addChild(node3);
  26. node.addChild(node4);
  27. Node node51 = new Node(8.0);
  28. Node node52 = new Node(7.0);
  29. node5.addChild(node51);
  30. node5.addChild(node52);
  31. node.addChild(node5);
  32. Node node11 = new Node(9.0);
  33. Node node12 = new Node(5.5);
  34. node1.addChild(node11);
  35. node1.addChild(node12);
  36. Node node21 = new Node(5.7);
  37. Node node22 = new Node(12.0);
  38. node2.addChild(node21);
  39. node2.addChild(node22);
  40. Node node31 = new Node(13.0);
  41. Node node32 = new Node(1.0);
  42. node22.addChild(node31);
  43. node22.addChild(node32);
  44. return node;
  45. }
  46. }
  47.  
  48. class StackNode {
  49. public Node node;
  50. public boolean largerChildrenPushed;
  51. public StackNode(Node n) {
  52. this.node = n;
  53. this.largerChildrenPushed = false;
  54. }
  55. }
  56.  
  57. class Ideone
  58. {
  59. public static void process(Node node) {
  60. Stack st = new Stack();
  61. st.push(new StackNode(node));
  62. while(!st.empty()) {
  63. StackNode stParent = (StackNode)st.pop();
  64. Node parent = stParent.node;
  65.  
  66. if(!stParent.largerChildrenPushed) {
  67. for (int i = parent.children.size() - 1; i >= 0; i--) {
  68. Node child = parent.children.get(i);
  69. if (child.value >= parent.value) {
  70. st.push(new StackNode(child));
  71. }
  72. }
  73. st.push(stParent);
  74. stParent.largerChildrenPushed = true;
  75. for (int i = parent.children.size() - 1; i >= 0; i--) {
  76. Node child = parent.children.get(i);
  77. if (child.value < parent.value) {
  78. st.push(new StackNode(child));
  79. }
  80. }
  81. }
  82. else {
  83. System.out.println(parent.value);
  84. }
  85. }
  86. }
  87.  
  88. public static void main (String[] args) throws java.lang.Exception
  89. {
  90. process(Node.createSample());
  91. }
  92. }
Success #stdin #stdout 0.04s 711168KB
stdin
Standard input is empty
stdout
5.7
6.0
1.0
12.0
13.0
5.0
8.0
7.0
10.0
9.0
5.5
15.0
11.0
14.0