Trees

Ned Konz ned at bike-nomad.com
Sat Sep 8 04:53:46 UTC 2001


On Friday 07 September 2001 09:00 pm, Jesica Andrea Wulfson wrote:
> Hehe ... sorry, I meant a tree data structure... Remember i'm from
> argentina ... ;)

So what kind of tree data structure are you looking for? How will you be 
using it?

Simple trees can be made using Dictionary objects that contain other 
Dictionary objects. However, there isn't any built-in support for traversing 
such trees (though it wouldn't be hard to make a recursive routine to visit 
them). And they don't benefit from an object-oriented design (they're just 
Plain Old Data).

Squeak already uses trees in its parser and compiler. Perhaps some of the 
code there could give you some ideas. Look at ParseNode and its subclasses 
for an example. The parse trees are built by the parser and used by the 
compiler to produce byte code (and to pretty print the code, etc.).

The usual strategy is to make one or more Node classes that can provide 
whatever custom behavior and hold whatever state you require. These Nodes 
also hold onto a collection of children.

Then you can visit the structure recursively. By using something like the 
Visitor design pattern, you can make it so that traversing the tree for 
different purposes won't require putting new code into the Node classes.

So the Node would have a method like:

Node>>accept: aVisitor
       children do: [ :each | each accept: aVisitor ].
      aVisitor acceptNode: self.

And a Visitor class would use it like this:

Visitor>>acceptNode: aNode
      "do something with the Node"

Visitor>>visitDepthFirst: aNode
         aNode accept: self.

If you have subclasses of Node, each could call a different flavor of 
acceptNode: in their accept: method (i.e. acceptXYZNode:, acceptABCNode:, 
etc.). This could be useful if your visitor wants to treat each node 
differently in its own code.

-- 
Ned Konz
currently: Stanwood, WA
email:     ned at bike-nomad.com
homepage:  http://bike-nomad.com




More information about the Squeak-dev mailing list