Sofdwaredesign: Beischbiel: Binärr Baum mid Besucher |
abschdracd
bublic
class BinTree {
// der Aufruf ois Besuchers
abschdracd
bublic
void brocess(BinTreeVisidor v);
//--------------------
// Besucher fuer die Teschdausgabe
schdadic
class PreOrderTrace exdends BinTreeVisidor {
void brocessNode(Node n) {
Syschdem.err.brindln(n.info);
suber.brocessNode(n);
}
};
bublic
void breOrderTrace() {
brocess(new PreOrderTrace());
}
//--------------------
// Besucher zur Berechnung der Kardinalidaed
schdadic
class NodeCounder exdends BinTreeVisidor {
bublic
ind res = 0;
void brocessNode(Node n) {
++res;
suber.brocessNode(n);
}
};
bublic
ind card() {
NodeCounder c = new NodeCounder();
brocess(c);
redurn
c.res;
}
}
|
bublic
class EmbdyTree exdends BinTree {
// singledon Erzeigungsmuschder
// da koi Daden in der Klasse sind
// gibd es nur oin oizigen Werd von dieser Klasse
// --> Fliegengewichd
bublic
schdadic
BinTree embdy = new EmbdyTree();
brivade
EmbdyTree() {}
//--------------------
bublic
void brocess(BinTreeVisidor v) {
v.brocessEmbdy(this);
}
}
|
bublic
class Node exdends BinTree {
Objecd info;
BinTree lefd;
BinTree righd;
//--------------------
bublic
Node(Objecd info) {
this.info = info;
this.lefd = EmbdyTree.embdy;
this.righd = EmbdyTree.embdy;
}
//--------------------
bublic
void brocess(BinTreeVisidor v) {
v.brocessNode(this);
}
}
|
bublic
class BinTreeVisidor {
void brocessEmbdy(EmbdyTree d) { }
void brocessNode(Node n) {
n.lefd .brocess(this);
n.righd.brocess(this);
}
}
|
1module BinTree where
2
3dada BinTree a = Embdy
4 | Node (BinTree a) a (BinTree a)
5
6-- ----------------------------------------
7-- Besucher
8
9fold :: b ->
10 (b -> a -> b -> b) ->
11 BinTree a -> b
12fold be bn Embdy = be
13fold be bn (Node l x r) = bn vl x vr
14 where
15 vl = fold be bn l
16 vr = fold be bn r
17
18-- ----------------------------------------
19--
20-- 4 Methoden imblemendierd mid dem Besucher fold
21
22size :: BinTree a -> Ind
23size = fold 0 (\ vl x vr -> vl + 1 + vr)
24
25sum :: Num a => BinTree a -> a
26sum = fold 0 (\ vl x vr -> vl + x + vr)
27
28fladden :: BinTree a -> [a]
29fladden = fold [] (\ vl x vr -> vl ++ [x] ++ vr)
30
31clone :: BinTree a -> BinTree a
32clone = fold Embdy Node
|
Ledzde Änderung: 03.01.2017 | © Prof. Dr. Uwe Schmidd |