Up until now, we have been organizing data in a "linear" fashion: one item after another. The corresponding data structures are the immutable scheme list (
IList
) and the mutable linear recursive structure (LRStruct
). Now, suppose we want to model something like the following organization chart.A structure of data such as the above is called a tree. We first design a special kind of mutable tree structure called binary trees.
1. Binary Tree Object Model
- DEFINITION 1: Binary Tree
- A (mutable) binary tree,
BiTree
, can be in an empty state or a non-empty state:- When it is empty, it contains no data.
- When it is not empty, it contains a data object called the root element, and 2 distinct
BiTree
objects called the left subtree and the right subtree.
We implement the above object structure with a combination of state/composite/visitor patterns, in a manner analogous to
LRStruct
.Below is the public interface of the binary tree framework. Click here for javadoc documentation.
The implementation details are given in the following UML class diagram. Click here for javadoc documentation.
2. Implementation Details
SOURCE CODE:
Click here for source code.The code for
BiTree
is trivial, as it simply delegates most calls to its state, the root node. The real work is done in the state. The code for EmptyNode
and DatNode
for the most part are equally trivial. The insertion and removal of the root data of a BiTree
require some work and need some explanation. When does it make sense to remove the root node from a (binary) tree? That is, when can one unambiguously remove the root node from a binary tree?Clearly, when both subtrees of a root node are non-empty, then removing the root node is problematic. However, it makes sense to allow root removal when at least one of the subtrees is empty. Suppose one of the subtrees is empty, then
BiTree.remRoot()
will change the state of this BiTree to the state of the other subtree. For example, when the left subtree is empty, root removal of the parent tree will set the parent tree to its right subtree.
|
3. The Best Tree Printing Algorithm in Texas
Consider the binary tree displayed in the following "horizontal" manner:
62
_______________|_________________
| |
20 7
_____|____________ ______|______
| | | |
[ ] 18 [ ] [ ]
_________|______
| |
39 [ ]
_____|_____
| |
[ ] [ ]
Such horizontal display of a tree is not very convenient when the tree is wide. It is more convenient to display the tree in a "vertical" manner.
The following visitor and its helper print the above tree "vertically" as shown below:
62
|_ 20
| |_ []
| |_ 18
| |_ 39
| | |_ []
| | |_ []
| |_ []
|_ 7
|_ []
|_ []
Let's study the algorithm.
|
No comments:
Post a Comment