|
| 1 | +package lambdasinaction.chap13; |
| 2 | + |
| 3 | +public class PersistentTree { |
| 4 | + |
| 5 | + public static void main(String[] args) { |
| 6 | + Tree t = new Tree("Mary", 22, |
| 7 | + new Tree("Emily", 20, |
| 8 | + new Tree("Alan", 50, null, null), |
| 9 | + new Tree("Georgie", 23, null, null) |
| 10 | + ), |
| 11 | + new Tree("Tian", 29, |
| 12 | + new Tree("Raoul", 23, null, null), |
| 13 | + null |
| 14 | + ) |
| 15 | + ); |
| 16 | + |
| 17 | + // found = 23 |
| 18 | + System.out.println(lookup("Raoul", -1, t)); |
| 19 | + // not found = -1 |
| 20 | + System.out.println(lookup("Jeff", -1, t)); |
| 21 | + |
| 22 | + Tree f = fupdate("Jeff", 80, t); |
| 23 | + // found = 80 |
| 24 | + System.out.println(lookup("Jeff", -1, f)); |
| 25 | + |
| 26 | + Tree u = update("Jim", 40, t); |
| 27 | + // t was not altered by fupdate, so Jeff is not found = -1 |
| 28 | + System.out.println(lookup("Jeff", -1, u)); |
| 29 | + // found = 40 |
| 30 | + System.out.println(lookup("Jim", -1, u)); |
| 31 | + |
| 32 | + Tree f2 = fupdate("Jeff", 80, t); |
| 33 | + // found = 80 |
| 34 | + System.out.println(lookup("Jeff", -1, f2)); |
| 35 | + // f2 built from t altered by update() above, so Jim is still present = 40 |
| 36 | + System.out.println(lookup("Jim", -1, f2)); |
| 37 | + } |
| 38 | + |
| 39 | + static class Tree { |
| 40 | + private String key; |
| 41 | + private int val; |
| 42 | + private Tree left, right; |
| 43 | + |
| 44 | + public Tree(String k, int v, Tree l, Tree r) { |
| 45 | + key = k; |
| 46 | + val = v; |
| 47 | + left = l; |
| 48 | + right = r; |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + public static int lookup(String k, int defaultval, Tree t) { |
| 53 | + if (t == null) |
| 54 | + return defaultval; |
| 55 | + if (k.equals(t.key)) |
| 56 | + return t.val; |
| 57 | + return lookup(k, defaultval, k.compareTo(t.key) < 0 ? t.left : t.right); |
| 58 | + } |
| 59 | + |
| 60 | + public static Tree update(String k, int newval, Tree t) { |
| 61 | + if (t == null) |
| 62 | + t = new Tree(k, newval, null, null); |
| 63 | + else if (k.equals(t.key)) |
| 64 | + t.val = newval; |
| 65 | + else if (k.compareTo(t.key) < 0) |
| 66 | + t.left = update(k, newval, t.left); |
| 67 | + else |
| 68 | + t.right = update(k, newval, t.right); |
| 69 | + return t; |
| 70 | + } |
| 71 | + |
| 72 | + public static Tree fupdate(String k, int newval, Tree t) { |
| 73 | + return (t == null) ? |
| 74 | + new Tree(k, newval, null, null) : |
| 75 | + k.equals(t.key) ? |
| 76 | + new Tree(k, newval, t.left, t.right) : |
| 77 | + k.compareTo(t.key) < 0 ? |
| 78 | + new Tree(t.key, t.val, fupdate(k,newval, t.left), t.right) : |
| 79 | + new Tree(t.key, t.val, t.left, fupdate(k,newval, t.right)); |
| 80 | + } |
| 81 | + |
| 82 | +} |
0 commit comments