/examples/kilim/examples/Tree.java

http://github.com/kilim/kilim · Java · 82 lines · 53 code · 14 blank · 15 comment · 6 complexity · cd9739343a623f0476f18b47e0961fe1 MD5 · raw file

  1. /* Copyright (c) 2006, Sriram Srinivasan
  2. *
  3. * You may distribute this software under the terms of the license
  4. * specified in the file "License"
  5. */
  6. package kilim.examples;
  7. import kilim.Generator;
  8. import kilim.Pausable;
  9. /**
  10. * This example illustrates two 'generators' that walk a tree, one in pre-order
  11. * and another in post-order.
  12. *
  13. * A generator is an iterator that generates a value (in this
  14. * case the nodes of the tree) each time its execute() method
  15. * 'yields' a value.
  16. *
  17. * Also, @see kilim.examples.Fib
  18. */
  19. public class Tree {
  20. public String _val;
  21. Tree _left;
  22. Tree _right;
  23. public static void main(String[] args) {
  24. Tree t = new Tree("root",
  25. new Tree("a",
  26. new Tree("a1"),
  27. new Tree("a2")),
  28. new Tree("b",
  29. new Tree ("b1"),
  30. new Tree ("b2")));
  31. System.out.println("Pre-order traversal:");
  32. for (String s: new Pre(t)) {
  33. System.out.println(s);
  34. }
  35. System.out.println("Post-order traversal");
  36. for (String s: new Post(t)) {
  37. System.out.println(s);
  38. }
  39. }
  40. Tree(String s) {_val = s;}
  41. Tree(String s, Tree l, Tree r) {this(s); _left = l; _right = r;}
  42. }
  43. class Pre extends Generator<String> {
  44. Tree _t;
  45. Pre(Tree t) {_t = t;}
  46. public void execute() throws Pausable{
  47. walk(_t);
  48. }
  49. void walk(Tree t) throws Pausable {
  50. if (t == null) return;
  51. yield(t._val);
  52. walk(t._left);
  53. walk(t._right);
  54. }
  55. }
  56. class Post extends Generator<String> {
  57. Tree _t;
  58. Post(Tree t) {_t = t;}
  59. public void execute() throws Pausable {
  60. walk(_t);
  61. }
  62. void walk(Tree t) throws Pausable {
  63. if (t == null) return;
  64. walk(t._left);
  65. walk(t._right);
  66. yield(t._val);
  67. }
  68. }