PageRenderTime 21ms CodeModel.GetById 2ms app.highlight 13ms RepoModel.GetById 1ms app.codeStats 1ms

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