fork download
  1. import java.util.*;
  2. import java.lang.*;
  3. import java.io.*;
  4.  
  5. class Node {
  6. int value;
  7. Node left, right, parent;
  8.  
  9. public Node(int value) {
  10. this.value = value;
  11. }
  12.  
  13. public void setLeft(Node left) {
  14. this.left = left;
  15. left.parent = this;
  16. }
  17.  
  18. public void setRight(Node right) {
  19. this.right = right;
  20. right.parent = this;
  21. }
  22.  
  23. public Node first() {
  24. Node n = this;
  25. while (n.left != null) n = n.left;
  26. return n;
  27. }
  28.  
  29. public Node next() {
  30. if (right != null) return right.first();
  31. for (Node n = this; ; n = n.parent) {
  32. if (n.parent == null) return null;
  33. if (n == n.parent.left) return n.parent;
  34. }
  35. }
  36. }
  37.  
  38. class Ideone
  39. {
  40. public static void main (String[] args) throws java.lang.Exception
  41. {
  42. // 8
  43. // / \
  44. // / \
  45. // / \
  46. // 3 10
  47. // / \ \
  48. // / \ \
  49. // 1 6 14
  50. // / \ /
  51. // 4 7 13
  52. Node n8 = new Node(8),
  53. n3 = new Node(3), n10 = new Node(10),
  54. n1 = new Node(1), n6 = new Node(6), n14 = new Node(14),
  55. n4 = new Node(4), n7 = new Node(7), n13 = new Node(13);
  56. Node root = n8;
  57. n8.setLeft(n3); n8.setRight(n10);
  58. n3.setLeft(n1); n3.setRight(n6);
  59. n6.setLeft(n4); n6.setRight(n7);
  60. n10.setRight(n14);
  61. n14.setLeft(n13);
  62.  
  63. Node n = root.first();
  64. while (n != null) {
  65. System.out.printf("%d ", n.value);
  66. n = n.next();
  67. }
  68. }
  69. }
Success #stdin #stdout 0.1s 33856KB
stdin
Standard input is empty
stdout
1 3 4 6 7 8 10 13 14