Some design rationale

We're going to split the collection into two classes: TreeNode and Tree. This will allow us to separate the design into the essential data collection, and a Pythonic Façade design pattern required to match other collections. 

The TreeNode class will contain the item as well as the more, less, and parent references. This is the core collection of values. It handles insertion and removal. Also, searching for a particular item in order to use __contains__() or discard() will be delegated to the TreeNode class.

The essential search algorithm's outline looks like this.

  • If the target item is equal to the self item, then return self.
  • If the target item is less than self.item, then recursively use less.find(target item).
  • If the target item is greater than self.item, then recursively use more.find(target.item).

We'll use similar delegation to the TreeNode class for more of the real work of maintaining the tree structure.

We'll use the Façade design pattern to wrap details of the TreeNode with a Pythonic interface. This will define the visible, external definition the Tree itself. A Façade design can also be called a wrapper; the idea is to add features required for a particular interface. The Tree class provides the external interface required by a MutableSet ABC and keeps these requirements distinct from the implementation details in the TreeNode class.

The algorithms can be somewhat simpler if there's a root node that's empty and always compares less than all other key values. This can be challenging in Python because we don't know in advance what types of data the nodes might have; we can't easily define a bottom value for the root node. Instead, we'll use a special case value of None, and endure the overheads of if statements checking for the root node.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset