by cperciva · 16y ago · 0 comments
class Node {
static const Node EMPTY_NODE = Node();
String key;
String value;
Node left = EMPTY_NODE;
Node right = EMPTY_NODE;
Node(String key, String value) {
this.key = key;
this.value = value;
}
static void traverseInorder(Node n, Visitor v) {
if (n.left != EMPTY_NODE) {
traverseInorder(left, v);
}
v.visit (n);
if (n.right != EMPTY_NODE) {
traverseInorder(right, v);
}
}
} class Node {
// May not be a real situation for a Node class,
// but makes a point.
Node getLeft() {
return left;
}
}
// No more checks against NULL. In fact code becomes simpler for
// the user of the library.
node.getLeft().getLeft().getValue();
I don't think the class definition is much too complicated, except for the declaration of the EMPTY field. What we need is a non-mutable, class-wide, default object, not null. We don't need to explicitly declare this object, if the language does that for us and make it accessible through a keyword - say 'default': if (n.left != default) {
traverse(n.left);
}